package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.AddressEnum;
import com.xbongbong.paas.enums.ComboTypeEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.field.MultiUnitItemPoJo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.field.UnitItemPoJo;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.MultiUnitPricePoJo;
import com.xbongbong.paas.pojo.ProductFieldPojo;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.imports.CellTitlePojo;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.RowGroupPojo;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.pojo.DataPermissionParamsPojo;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.ImportEnum;
import com.xbongbong.pro.enums.PaasStageEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.ImportErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.InvoiceErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.OutstockErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ProductErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SupplierContactErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.WarehouseErrorCodeEnum;
import com.xbongbong.pro.export.pojo.ExportLinkDataPojo;
import com.xbongbong.pro.form.pojo.dto.FormConfigGetDTO;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.export.ImportConstant;
import com.xbongbong.saas.domain.entity.ProductBaseInfoEntity;
import com.xbongbong.saas.domain.entity.ProductStockEntity;
import com.xbongbong.saas.domain.entity.ProductStockInfoEntity;
import com.xbongbong.saas.domain.entity.ProductUnitPriceEntity;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.enums.BirthdayTypeEnum;
import com.xbongbong.saas.enums.FormConfigEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.base.CommunicateBaseEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.StockProductEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.product.PriceProductEnum;
import com.xbongbong.saas.enums.product.PriceSetEnum;
import com.xbongbong.saas.enums.subform.ProductStockSubFormEnum;
import com.xbongbong.saas.enums.subform.ProductWarehouseSubFormEnum;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import com.xbongbong.saas.service.toolbox.help.FundSetHelp;
import com.xbongbong.saas.toolbox.help.TimeUtil;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 导入相关helper
 *
 * @author GuoJun.HU
 * @date 2019/4/29 13:53
 * @since V1.0
 */
@Component
public class ImportHelper {

    @Resource
    private EsHelper esHelper;
    @Resource
    private AttrDecimalPrecisionHelper attrDecimalPrecisionHelper;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private FormDataListAnalysisDataHelp formDataListAnalysisDataHelp;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private FundSetHelp fundSetHelp;
    @Resource
    private RelativeProductHelp relativeProductHelp;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private CommonHelp commonHelp;

    private static final Logger LOG = LoggerFactory.getLogger(ImportHelper.class);

    public static List<Integer> commonHandleFieldType = new ArrayList<Integer>() {
        {
            add(FieldTypeEnum.USER.getType());
            add(FieldTypeEnum.USER_GROUP.getType());
            add(FieldTypeEnum.STAR.getType());
            add(FieldTypeEnum.COMBO.getType());
            add(FieldTypeEnum.OWNERID.getType());
            add(FieldTypeEnum.COUSERID.getType());
            add(FieldTypeEnum.DEPARTMENTID.getType());
            add(FieldTypeEnum.DEPT_GROUP.getType());
            add(FieldTypeEnum.DEPT.getType());
            add(FieldTypeEnum.RADIO_GROUP.getType());
            add(FieldTypeEnum.CHECKBOX_GROUP.getType());
            add(FieldTypeEnum.COMBO_CHECK.getType());
            add(FieldTypeEnum.ADDTIME.getType());
            add(FieldTypeEnum.UPDATETIME.getType());
            add(FieldTypeEnum.ENDTIME.getType());
            add(FieldTypeEnum.DATETIME.getType());
            add(FieldTypeEnum.CLOSETIME.getType());
            add(FieldTypeEnum.CREATORID.getType());
            add(FieldTypeEnum.PURCHASEABLE_GOODS.getType());
            add(FieldTypeEnum.STAGE_THRUSTER.getType());
        }
    };



    /**
     * 将数据分页，以便于一页一页的插入
     *
     * @param jsonArray 数据
     * @return List
     */
    public List<JSONArray> resolveDataJSONArray(JSONArray jsonArray) {
        List<JSONArray> dataList = new ArrayList<>();
        JSONArray dataJsonArray = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            if (dataJsonArray.size() > ImportConstant.ONE_INSERT_DATA_NUM) {
                dataList.add(dataJsonArray);
                dataJsonArray = new JSONArray();
            }
            dataJsonArray.add(jsonArray.get(i));
        }
        if (jsonArray.size() <= ImportConstant.ONE_INSERT_DATA_NUM) {
            dataList.add(dataJsonArray);
        }
        return dataList;
    }

    /**
     * 通过表头名称获取列索引
     *
     * @param titlePojoList 表头
     * @param title         标题
     * @param parentTitle   父标题
     * @return Integer
     * @author GuoJun.HU
     * @date 2019/4/29 16:19
     * @since V1.0
     */
    public Integer getColumnIndexByTitle(List<CellTitlePojo> titlePojoList, String title, String parentTitle) {
        for (CellTitlePojo titlePojo : titlePojoList) {
            if (Objects.equals(titlePojo.getParentTitle(), parentTitle) && Objects.equals(titlePojo.getTitle(), title)) {
                return titlePojo.getColumnIndex();
            }
        }
        return null;
    }

    /**
     * 通过表头名称获取列索引
     *
     * @param titlePojoList 表头
     * @param title         标题
     * @param parentTitle   父标题
     * @return Integer
     * @author GuoJun.HU
     * @date 2019/4/29 16:19
     * @since V1.0
     */
    public Integer getColumnIndexByAllTitle(List<CellTitlePojo> titlePojoList, String title, String parentTitle, String secondParentTitle, String thirdParentTitle) {
        for (CellTitlePojo titlePojo : titlePojoList) {
            if (Objects.equals(titlePojo.getParentTitle(), parentTitle) && Objects.equals(titlePojo.getTitle(), title)
                    && Objects.equals(titlePojo.getSecondParentTitle(), secondParentTitle)
                    && Objects.equals(titlePojo.getThirdParentTitle(), thirdParentTitle)) {
                return titlePojo.getColumnIndex();
            }
        }
        return null;
    }
    /**
     * 通过表头名称获取列索引
     *
     * @param titlePojoList 表头
     * @param title         标题
     * @param parentTitle   父标题
     * @return Integer
     * @author GuoJun.HU
     * @date 2019/4/29 16:19
     * @since V1.0
     */
    public Integer getColumnIndexBySubTitleAndTitle(List<CellTitlePojo> titlePojoList, String title, String parentTitle, String subParentTitle) {
        for (CellTitlePojo titlePojo : titlePojoList) {
            if (Objects.equals(titlePojo.getParentTitle(), parentTitle) && Objects.equals(titlePojo.getTitle(), title)) {
                return titlePojo.getColumnIndex();
            }
        }
        return null;
    }
    /**
     * 通过attr从解释中获取attrName
     *
     * @param fieldAttrList fieldAttrList
     * @param attr          字段
     * @return attrName
     */
    public String getAttrNameFromExplainByAttr(List<FieldAttrEntityForImport> fieldAttrList, String attr) {
        if (attr.contains(StringConstant.POINT)) {
            // 子表单
            String[] split = attr.split("\\.");
            for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                if (Objects.equals(fieldAttrEntity.getAttr(), split[0])) {
                    SubFormPoJo subForm = fieldAttrEntity.getSubForm();
                    if (Objects.nonNull(subForm)) {
                        for (FieldAttrEntity item : subForm.getItems()) {
                            if (Objects.equals(item.getAttr(), split[1])) {
                                return item.getAttrName();
                            }
                        }

                    }
                }
            }

        } else {
            for (FieldAttrEntity fieldAttrEntity : fieldAttrList) {
                if (Objects.equals(fieldAttrEntity.getAttr(), attr)) {
                    return fieldAttrEntity.getAttrName();
                }
            }
        }
        return null;
    }

    /**
     * 通过分组标志获取对应的一组数据
     *
     * @param valueList     数据
     * @param groupTagValue 分组标志
     * @return RowGroupPojo
     * @author GuoJun.HU
     * @date 2019/4/29 16:21
     * @since V1.0
     */
    public RowGroupPojo getGroupByUniqueTag(List<RowGroupPojo> valueList, String groupTagValue) {
        if (groupTagValue == null) {
            return null;
        }
        if (!valueList.isEmpty()) {
            RowGroupPojo rowGroupPojo = valueList.get(valueList.size() - 1);
            if (Objects.equals(rowGroupPojo.getGroupTagValue(), groupTagValue) && StringUtil.isNotEmpty(groupTagValue)) {
                return rowGroupPojo;
            }
        }
//        for (RowGroupPojo rowGroupPojo : valueList) {
//            if (Objects.equals(rowGroupPojo.getGroupTagValue(), groupTagValue)) {
//                return rowGroupPojo;
//            }
//        }
        return null;
    }

    /**
     * 通过列索引 获取某一行在这一列对应的值
     *
     * @param cellValueList 某一行的数据
     * @param columnIndex   列索引
     * @return Object
     * @author GuoJun.HU
     * @date 2019/4/29 16:22
     * @since V1.0
     */
    public Object getValueByColumnIndex(List<CellValuePojo> cellValueList, Integer columnIndex) {
        for (CellValuePojo valuePojo : cellValueList) {
            if (Objects.equals(valuePojo.getColumnIndex(), columnIndex)) {
                return valuePojo.getValue();
            }
        }
        return null;
    }

    /**
     * 解释中是否有子表单
     *
     * @param fieldAttrList 解释
     * @return boolean
     * @author GuoJun.HU
     * @date 2019/4/29 16:23
     * @since V1.0
     */
    public Integer hasSubForm(List<FieldAttrEntityForImport> fieldAttrList) {
        Integer addIndex = 0;
        Integer maxIndex = addIndex;
        for (FieldAttrEntity fieldAttrEntity : fieldAttrList) {
            addIndex = 0;
            if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SUB_FORM.getType())) {
                addIndex ++;
                List<FieldAttrEntityForImport> fieldAttrEntityForImportList =JSON.parseArray(JSON.toJSONString(fieldAttrEntity.getSubForm().getItems()), FieldAttrEntityForImport.class);
                addIndex += hasSubForm(fieldAttrEntityForImportList);
            }
            if (maxIndex < addIndex) {
                maxIndex = addIndex;
            }
        }
        return maxIndex;
    }

    /**
     * 获取子表单深度
     *
     * @param fieldAttrEntityList 解释
     * @param addIndex 深度
     */
    public void getSubFormDepth(List<? extends FieldAttrEntity> fieldAttrEntityList, Integer addIndex) {
        for (FieldAttrEntity fieldAttrEntity : fieldAttrEntityList) {
            if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SUB_FORM.getType())) {
                addIndex ++;
                List<? extends FieldAttrEntity> fieldAttrEntityForImportList = fieldAttrEntity.getSubForm().getItems();
                getSubFormDepth(fieldAttrEntityForImportList, addIndex);
            }
        }
    }


    /**
     * 通过解释计算理论上应该有多少列
     *
     * @param fieldEntityArray 解释
     * @return 多少列
     * @author GuoJun.HU
     * @date 2019/4/29 16:25
     * @since V1.0
     */
    public Integer calculateLengthByExplain(JSONArray fieldEntityArray) {
        int length = 0;
        for (Object object : fieldEntityArray) {
            JSONObject jsonObject = (JSONObject) object;
            Integer fieldType = jsonObject.getInteger("fieldType");
            if (fieldType.equals(FieldTypeEnum.SUB_FORM.getType())) {
                JSONArray subJsonArray = jsonObject.getJSONObject("subForm").getJSONArray("items");
                length = subJsonArray.size() + length;
            } else {
                length++;
            }
        }
        return length;
    }

    /**
     * 如果是必填字段 则在标题上显示*号
     *
     * @param fieldAttrEntity 解释
     * @author GuoJun.HU
     * @date 2019/5/1 11:20
     * @since V1.0
     */
    public void setTitleRequiredTag(FieldAttrEntityForImport fieldAttrEntity) {
        Locale locale = LocaleContextHolder.getLocale();
        fieldAttrEntity.setAttrName(fieldAttrEntity.getAttrName());
        fieldAttrEntity.setAttrNameEn(fieldAttrEntity.getAttrNameEn());
        if (Objects.equals(fieldAttrEntity.getRequired(), 1)) {
            fieldAttrEntity.setAttrName(fieldAttrEntity.getAttrName() + ImportConstant.TITLE_REQUIRED_TAG);
            if (Objects.equals(locale.getLanguage(), I18nStringConstant.ENGLISH_LANGUAGE) && Objects.nonNull(fieldAttrEntity.getAttrNameEn())) {
                fieldAttrEntity.setAttrNameEn(fieldAttrEntity.getAttrName() + ImportConstant.TITLE_REQUIRED_TAG);
            }
        }
    }

    /**
     * 根据字段类型格式化导入的子表单数据
     * @param rowValueList
     * @param titlePojoList
     * @param importFormDataDTO
     * @param fieldAttr
     * @param dataJson
     */
    public void formatSubFormValue4Import(List<List<CellValuePojo>> rowValueList, List<CellTitlePojo> titlePojoList, ImportFormDataDTO importFormDataDTO, FieldAttrEntityForImport fieldAttr, JSONObject dataJson) throws XbbException {
        String attr = fieldAttr.getAttr();
        Integer fieldType = fieldAttr.getFieldType();
        String parentTitle = fieldAttr.getAttrName();
        SubFormPoJo subFormPoJo = fieldAttr.getSubForm();
        List<FieldAttrEntityForImport> subFieldAttrList = JSON.parseArray(JSON.toJSONString(subFormPoJo.getItems(), SerializerFeature.DisableCircularReferenceDetect), FieldAttrEntityForImport.class);
        if (Objects.equals(fieldAttr.getAttrType(), FieldTypeEnum.ADDRESS.getEsalias())) {
            // 地址根据es索引前缀判断
            List<CellValuePojo> subFormCellValueList = rowValueList.get(0);
            JSONObject subFormItem = getDataObject(titlePojoList, fieldAttr, importFormDataDTO, subFieldAttrList, subFormCellValueList);
            if (!subFormItem.isEmpty()) {
                dataJson.put(attr, subFormItem);
            }
        } else if (Objects.equals(fieldAttr.getSaasAttr(), ContactEnum.BIRTHDAY.getSaasAttr())) {
            // 生日根据saasAttr判断
            List<CellValuePojo> subFormCellValueList = rowValueList.get(0);
            JSONObject subFormItem = new JSONObject();
            for (FieldAttrEntityForImport subFormFieldAttr : subFieldAttrList) {
                String subAttrName = subFormFieldAttr.getAttrName();
                String subAttr = subFormFieldAttr.getAttr();
                Integer columnIndex = getColumnIndexByTitle(titlePojoList, subAttrName, parentTitle);
                Object subFormCellValue = getValueByColumnIndex(subFormCellValueList, columnIndex);
                if (Objects.equals(subAttr, ImportEnum.BIRTHDAY_FLAG.getAttr())) {
                    if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                        continue;
                    }
                    BirthdayTypeEnum birthdayTypeEnum = BirthdayTypeEnum.getByText(subFormCellValue.toString());
                    subFormItem.put(subAttr, birthdayTypeEnum.getValue());
                }
                if (Objects.equals(subAttr, ImportEnum.BIRTHDAY.getAttr())) {
                    if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                        continue;
                    }
                    Long excelTime = DateTimeUtil.getExcelTime(subFormCellValue.toString());
                    if (Objects.isNull(excelTime) || excelTime == 0L) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.FORMAT_INVALID, fieldAttr.getAttrName());
                    }
                    subFormItem.put(subAttr, DateTimeUtil.getStringEpochSecond(excelTime, DateTimeUtil.SDFDate));
                }
            }
            if (!subFormItem.isEmpty()) {
                if (Objects.nonNull(subFormItem.get(ImportEnum.BIRTHDAY.getAttr())) && Objects.isNull(subFormItem.get(ImportEnum.BIRTHDAY_FLAG.getAttr()))) {
                    subFormItem.put(ImportEnum.BIRTHDAY_FLAG.getAttr(), 0);
                }
                dataJson.put(attr, subFormItem);
            }
        } else if (Objects.equals(fieldAttr.getSaasAttr(), CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getSaasAttr())) {
            // 跟进业务根据saasAttr判断
            Integer columnIndex = getColumnIndexByTitle(titlePojoList, ImportEnum.COMMUNICATE_BUSINESS_TYPE.getAttrName(), parentTitle);
            List<CellValuePojo> subFormCellValueList = rowValueList.get(0);
            Object subCellValue = getValueByColumnIndex(subFormCellValueList, columnIndex);
            if (Objects.nonNull(subCellValue) && StringUtil.isNotEmpty(subCellValue.toString())) {
                subCellValue = subCellValue.toString();
                JSONObject jsonObject = new JSONObject();
                if (Objects.equals(subCellValue, XbbRefTypeEnum.CONTRACT.getName()) || Objects.equals(subCellValue, XbbRefTypeEnum.ORDER.getName())) {
                    jsonObject.put(StringConstant.BUSINESS_TYPE, XbbRefTypeEnum.CONTRACT.getCode());
                } else if (Objects.equals(subCellValue, XbbRefTypeEnum.SALES_OPPORTUNITY.getName())) {
                    jsonObject.put(StringConstant.BUSINESS_TYPE, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
                } else if (Objects.equals(subCellValue, XbbRefTypeEnum.PURCHASE.getName())) {
                    jsonObject.put(StringConstant.BUSINESS_TYPE, XbbRefTypeEnum.PURCHASE.getCode());
                }
                columnIndex = getColumnIndexByTitle(titlePojoList, ImportEnum.COMMUNICATE_NAME.getAttrName(), parentTitle);
                Object nameCellValue = getValueByColumnIndex(subFormCellValueList, columnIndex);
                if (Objects.nonNull(nameCellValue) && StringUtil.isNotEmpty(nameCellValue.toString())) {
                    Map<String, Object> linkBusinessMap = fieldAttr.getLinkBusinessMap();
                    if (linkBusinessMap.containsKey(nameCellValue.toString())) {
                        jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, linkBusinessMap.get(nameCellValue.toString()));
                        jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, nameCellValue.toString());
                    } else {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_EXISTS_IN_SYSTEM, ImportEnum.COMMUNICATE_NAME.getAttrName());
                    }
                    dataJson.put(CommunicateBaseEnum.COMMUNICATE_BUSINESS.getAttr(), jsonObject);
                }
            }
        } else if (Objects.equals(fieldAttr.getLinkedType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            // 关联客户根据linkedType判断
            formatLinkCustomer2CustomerId(titlePojoList, dataJson, rowValueList, fieldAttr);
        }  else if (Objects.equals(fieldAttr.getAttrType(), FieldTypeEnum.LINK_FORM.getEsalias())
                && Objects.nonNull(fieldAttr.getSaasParticularAttributePoJo())
                && Objects.nonNull(fieldAttr.getSaasParticularAttributePoJo().getLinkBusinessType()))  {
            // 关联新建根据array标识和SaasParticularAttributePoJo的linkBusinessType判断
            JSONArray dataArr = new JSONArray();
            for (List<CellValuePojo> subFormCellValueList : rowValueList) {
                JSONObject dataObj = new JSONObject();
                JSONObject subFormItem = getDataObject(titlePojoList, fieldAttr, importFormDataDTO, subFieldAttrList, subFormCellValueList);
                if (subFormItem.isEmpty()) {
                    continue;
                }
                dataObj.put(StringConstant.JSON_DATA, subFormItem);
                dataObj.put(StringConstant.DATA_ID, null);
                String serialNo = subFormItem.getString(FieldTypeEnum.SERIALNO.getAlias());
                dataObj.put(FieldTypeEnum.SERIALNO.getAlias(), "");
                if (Objects.nonNull(serialNo) && StringUtil.isNotEmpty(serialNo)) {
                    dataObj.put(FieldTypeEnum.SERIALNO.getAlias(), serialNo);
                    subFormItem.remove(FieldTypeEnum.SERIALNO.getAlias());
                }
               /* if (Objects.nonNull(subFormItem.get(FieldTypeEnum.DEPARTMENTID.getAlias()))) {
                    JSONObject departmentObj = subFormItem.getJSONObject(FieldTypeEnum.DEPARTMENTID.getAlias());
                    if (departmentObj != null) {
                        Long departmentId = departmentObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                        dataObj.put(FieldTypeEnum.DEPARTMENTID.getAlias(), departmentId);
                        subFormItem.remove(FieldTypeEnum.DEPARTMENTID.getAlias());
                    }
                }*/
                if (!subFormItem.isEmpty()) {
                    dataArr.add(dataObj);
                }
            }
            dataJson.put(attr, dataArr);
        } else if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
            // 普通子表单
            JSONArray subJsonArray = new JSONArray();
            for (List<CellValuePojo> subFormCellValueList : rowValueList) {
                JSONObject subFormItem = getDataObject(titlePojoList, fieldAttr, importFormDataDTO, subFieldAttrList, subFormCellValueList);
                if (!subFormItem.isEmpty()) {
                    subJsonArray.add(subFormItem);
                }
            }
            if (!subJsonArray.isEmpty()) {
                dataJson.put(attr, subJsonArray);
            }
        }

    }

    public String getCustomerUniqueKey(List<List<CellValuePojo>> rowValueList, List<CellTitlePojo> titlePojoList, String parentTitle) {
        String uniqueKey = "";
        Integer customerNamecolumnIndex = getColumnIndexByTitle(titlePojoList, ImportEnum.LINK_CUSTOMER_NAME.getAttrName(), parentTitle);
        Integer customerPhonecolumnIndex = getColumnIndexByTitle(titlePojoList, ImportEnum.LINK_CUSTOMER_PHONE.getAttrName(), parentTitle);
        List<CellValuePojo> subFormCellValueList = rowValueList.get(0);
        Object nameCellValue = getValueByColumnIndex(subFormCellValueList, customerNamecolumnIndex);
        Object phoneCellValue = getValueByColumnIndex(subFormCellValueList, customerPhonecolumnIndex);
        boolean nameNotEmpty = Objects.nonNull(nameCellValue) && StringUtil.isNotEmpty(nameCellValue.toString());
        boolean phoneNotEmpty = Objects.nonNull(phoneCellValue) && StringUtil.isNotEmpty(phoneCellValue.toString());
        // fix : 26598 【成功部】导入联系人的时候，关联客户中写的客户名称前面或则后面有空格的话，会无法匹配，需要直接导入的时候前后空格去掉，包括其他的单据，例如合同、销售机会、报价单等
        if (nameNotEmpty && phoneNotEmpty) {
            uniqueKey = uniqueKey + nameCellValue.toString().trim() + phoneCellValue.toString().trim();
        } else if (phoneNotEmpty) {
            uniqueKey = uniqueKey + phoneCellValue.toString().trim();
        } else if (nameNotEmpty) {
            uniqueKey = uniqueKey + nameCellValue.toString().trim();
        }
        return uniqueKey;
    }

    /**
     * 遍历导入的子表单数据
     * @param titlePojoList
     * @param fieldAttr
     * @param importFormDataDTO
     * @param subFieldAttrList
     * @param subFormCellValueList
     * @return 子表单json对象
     */
    private JSONObject getDataObject(List<CellTitlePojo> titlePojoList, FieldAttrEntityForImport fieldAttr,
                                     ImportFormDataDTO importFormDataDTO, List<FieldAttrEntityForImport> subFieldAttrList, List<CellValuePojo> subFormCellValueList) throws XbbException{
        JSONObject subFormItem = new JSONObject();
        Boolean subDataNotEmpty = fieldAttr.getSubDataNotEmpty() == null ? false : fieldAttr.getSubDataNotEmpty();
        if (!subDataNotEmpty) {
            subDataNotEmpty = judgeSubFormHaveValue(titlePojoList, fieldAttr, subFieldAttrList, subFormCellValueList);
        }
        for (FieldAttrEntityForImport subFormFieldAttr : subFieldAttrList) {
            String subAttrName = subFormFieldAttr.getAttrName();
            String subAttr = subFormFieldAttr.getAttr();
            if (Objects.equals(subFormFieldAttr.getFieldType(), FieldTypeEnum.SUB_FORM.getType())) {
                subFormFieldAttr.setSubDataNotEmpty(subDataNotEmpty);
                formatSubFormValue4Import(Collections.singletonList(subFormCellValueList), titlePojoList, importFormDataDTO, subFormFieldAttr, subFormItem);
            } else {
                Integer columnIndex = getColumnIndexByTitle(titlePojoList, subAttrName, fieldAttr.getAttrName());
                Object subFormCellValue = getValueByColumnIndex(subFormCellValueList, columnIndex);
                if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                    if (subDataNotEmpty && Objects.equals(subFormFieldAttr.getRequired(), 1)) {
                        throw new XbbException(ImportErrorCodeEnum.API_ERROR_235007.getCode(), ImportErrorCodeEnum.API_ERROR_235007.getMsg(), fieldAttr.getAttrName() + subAttrName);
                    } else {
                        continue;
                    }
                }
                if (Objects.equals(subFormFieldAttr.getFieldType(), FieldTypeEnum.LINK_DATA.getType()) ){
                    if (Objects.equals(fieldAttr.getAttr(), CustomerManagementEnum.ADD_CONTACT.getAttr())) {
                        formatLinkData(subFormCellValue, subFormFieldAttr, subFormItem);
                    }
                    continue;
                }
                if (Objects.equals(subFormFieldAttr.getFieldType(), FieldTypeEnum.LINK_DATA_MULTI.getType())){
                    if (Objects.equals(fieldAttr.getAttr(), CustomerManagementEnum.ADD_CONTACT.getAttr())) {
                        formatLinkDataMulti(subFormCellValue, importFormDataDTO, subFormFieldAttr, subFormItem);
                    }
                    continue;
                }
                subFormItem.put(subAttr, subFormCellValue);
                if (commonHandleFieldType.contains(subFormFieldAttr.getFieldType())) {
                   formatCommonField(subFormItem, subFormFieldAttr, subFormCellValue);
                }
            }
        }
        return subFormItem;
    }

    private Boolean judgeSubFormHaveValue(List<CellTitlePojo> titlePojoList, FieldAttrEntityForImport fieldAttr, List<FieldAttrEntityForImport> subFieldAttrList, List<CellValuePojo> subFormCellValueList) {
        Boolean subDataNotEmpty = false;
        for (FieldAttrEntityForImport subFormFieldAttr : subFieldAttrList) {
            if (Objects.equals(subFormFieldAttr.getFieldType(), FieldTypeEnum.SUB_FORM.getType())) {
                List<FieldAttrEntityForImport> subSubFieldList = JSON.parseArray(JSON.toJSONString(subFormFieldAttr.getSubForm().getItems()), FieldAttrEntityForImport.class);
                subDataNotEmpty = judgeSubFormHaveValue(titlePojoList, subFormFieldAttr, subSubFieldList, subFormCellValueList);
                if (subDataNotEmpty) {
                    return subDataNotEmpty;
                }
            } else {
                Integer columnIndex = getColumnIndexByTitle(titlePojoList, subFormFieldAttr.getAttrName(), fieldAttr.getAttrName());
                Object subFormCellValue = getValueByColumnIndex(subFormCellValueList, columnIndex);
                if (Objects.nonNull(subFormCellValue) && StringUtil.isNotEmpty(subFormCellValue.toString())) {
                    subDataNotEmpty = true;
                    break;
                }
            }
        }
        return subDataNotEmpty;
    }


    /**
     * 人员（部门）多选将人员名字变为id数组
     *
     * @param subFormItem
     * @param subFormFieldAttr
     * @param subFormCellValue
     */
    public void formatUserOrDeptGroup4Import(JSONObject subFormItem, FieldAttrEntityForImport subFormFieldAttr, Object subFormCellValue) throws XbbException {
        Map<String, Object> linkBusinessMap = subFormFieldAttr.getLinkBusinessMap();
        String[] cellArr = subFormCellValue.toString().split(StringConstant.COMMA);
        List<ReturnUserAndDepartmentPojo> userArr = new ArrayList<>();
        String value = subFormCellValue.toString();
        for (int i = 0; i < cellArr.length; i ++) {
            if (linkBusinessMap.containsKey(cellArr[i])) {
                ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                if (linkBusinessMap.containsKey(value)) {
                    returnUserAndDepartmentPojo.setId(linkBusinessMap.get(value));
                }
                returnUserAndDepartmentPojo.setId(linkBusinessMap.get(cellArr[i]));
                userArr.add(returnUserAndDepartmentPojo);
            }
        }
        if (userArr.isEmpty()) {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235012, ImportErrorCodeEnum.API_ERROR_235012.getMsg(), subFormFieldAttr.getAttrName());
        }
        subFormItem.put(subFormFieldAttr.getAttr(), JSONArray.parseArray(JSON.toJSONString(userArr)));
    }

    /**
     * 人员（部门）单选将人员名字变为id
     *
     * @param subFormItem
     * @param subFormFieldAttr
     * @param subFormCellValue
     * @throws XbbException
     */
    public void formatUserOrDept4Import(JSONObject subFormItem, FieldAttrEntityForImport subFormFieldAttr, Object subFormCellValue) throws XbbException {
        Map<String, Object> linkBusinessMap = subFormFieldAttr.getLinkBusinessMap();
        String[] cellArr = subFormCellValue.toString().split(StringConstant.COMMA);
        if (cellArr.length > 1) {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235009, String.format(ImportErrorCodeEnum.API_ERROR_235009.getMsg(), subFormFieldAttr.getAttrName()));
        }
        ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
        if (linkBusinessMap.containsKey(cellArr[0])) {
            returnUserAndDepartmentPojo.setId(linkBusinessMap.get(cellArr[0]));
        } else  {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235012, ImportErrorCodeEnum.API_ERROR_235012.getMsg(), subFormFieldAttr.getAttrName());
        }
        subFormItem.put(subFormFieldAttr.getAttr(), JSON.toJSON(returnUserAndDepartmentPojo));
    }

    /**
     * 如果是分行导入的子表单，就加上 ^ 标记
     *
     * @param fieldAttrEntity 解释
     */
    public void setTitleNeedSeparatelyTag(FieldAttrEntityForImport fieldAttrEntity) {
        Locale locale = LocaleContextHolder.getLocale();
        boolean needImportSeparately = Objects.equals(fieldAttrEntity.getNeedImportSeparately(), ImportConstant.NEED_IMPORT_SEPARATELY);
        if (needImportSeparately) {
            fieldAttrEntity.setAttrName(fieldAttrEntity.getAttrName() + ImportConstant.TITLE_CAN_IMPORT_SEPARATELY);
            if (Objects.equals(locale.getLanguage(), I18nStringConstant.ENGLISH_LANGUAGE) && Objects.nonNull(fieldAttrEntity.getAttrNameEn())) {
                fieldAttrEntity.setAttrNameEn(fieldAttrEntity.getAttrName() + ImportConstant.TITLE_CAN_IMPORT_SEPARATELY);
            }

        }
    }

    /**
     * 关联业务封装
     *
     * @param dataJson
     * @param fieldAttr
     * @param cellValue
     */
    public void formatLinkBusinessValue4Import(JSONObject dataJson, FieldAttrEntityForImport fieldAttr, Object cellValue) throws XbbException {
        Map<String, Object> linkBusinessMap;
        if (Objects.nonNull(fieldAttr.getTempLinkBusinessMap())) {
            linkBusinessMap = fieldAttr.getTempLinkBusinessMap();
        } else {
            linkBusinessMap = fieldAttr.getLinkBusinessMap();
        }
        cellValue = cellValue.toString().replaceAll(StringConstant.CHINESE_COMMA, StringConstant.COMMA);
        String[] cellArr = cellValue.toString().split(StringConstant.COMMA);
        JSONArray linkBusinessArr = new JSONArray();
        for (int i= 0; i < cellArr.length; i ++) {
            if (linkBusinessMap.containsKey(cellArr[i])) {
                JSONObject linkBusinessObj = new JSONObject();
                Object linkBusiness = linkBusinessMap.get(cellArr[i]);
                if (linkBusiness instanceof PaasFormDataEntityExt) {
                    PaasFormDataEntityExt paasFormDataEntityExt = (PaasFormDataEntityExt) linkBusiness;
                    linkBusinessObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, paasFormDataEntityExt.getId());
                } else {
                    linkBusinessObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, linkBusinessMap.get(cellArr[i]));
                }
                linkBusinessObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, cellArr[i]);
                linkBusinessArr.add(linkBusinessObj);
            } else {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_EXISTS_IN_SYSTEM, fieldAttr.getAttrName());
            }
        }
        dataJson.put(fieldAttr.getAttr(), linkBusinessArr);
    }
    /**
     * 下拉值
     *
     * @param dataJson
     * @param fieldAttr
     * @param cellValue
     */
    public void formatDropDownValue4Import(JSONObject dataJson, FieldAttrEntityForImport fieldAttr, Object cellValue) throws XbbException {
        Integer comboType = fieldAttr.getComboType();
        if (Objects.equals(comboType, ComboTypeEnum.CUSTOM.getType())) {
            List<ItemPoJo> itemPoJoList = fieldAttr.getItems();
            boolean isOther = false;
            cellValue = Objects.nonNull(cellValue) ? cellValue : "";
            for (ItemPoJo itemPoJo : itemPoJoList) {
                if (Objects.equals(itemPoJo.getIsOther(),1)){
                    isOther = true;
                    if (Objects.equals(cellValue.toString().trim(), itemPoJo.getText().trim())) {
                        dataJson.put(fieldAttr.getAttr(), cellValue);
                        break;
                    }
                }
                if (Objects.equals(cellValue.toString().trim(), itemPoJo.getText().trim())) {
                    dataJson.put(fieldAttr.getAttr(), itemPoJo.getValue());
                    break;
                }
            }
            if (isOther && !dataJson.containsKey(fieldAttr.getAttr()) && StringUtil.isNotEmpty(cellValue.toString())) {
                dataJson.put(fieldAttr.getAttr(), cellValue);
            }
        } else {
            dataJson.put(fieldAttr.getAttr(), cellValue);
        }
        if (!dataJson.containsKey(fieldAttr.getAttr()) && Objects.equals(fieldAttr.getRequired(), 1)) {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235008, String.format(ImportErrorCodeEnum.API_ERROR_235008.getMsg(), fieldAttr.getAttrName()));
        }
    }

    /**
     * 导入时，将下拉框的值转换成具体的文本信息
     * @param formDataObj
     * @param fieldAttrEntity
     * @param cellValue
     */
    private void formatDropDownList4Import(JSONObject formDataObj, FieldAttrEntity fieldAttrEntity, Object cellValue) throws XbbException {
        List<String> list = new ArrayList<>(Arrays.asList(cellValue.toString().split(StringConstant.COMMA)));
        Integer comboType = fieldAttrEntity.getComboType();
        JSONArray jsonArray = new JSONArray();
        if (Objects.equals(comboType, ComboTypeEnum.CUSTOM.getType())) {
            List<ItemPoJo> itemPoJoList = fieldAttrEntity.getItems();
            for (ItemPoJo itemPoJo : itemPoJoList) {
                if (Objects.equals(itemPoJo.getIsOther(), BasicConstant.ONE)){
                    continue;
                }
                Iterator<String> iterator = list.iterator();
                while (iterator.hasNext()) {
                    String s = iterator.next();
                    if (Objects.equals(itemPoJo.getText(), s)) {
                        jsonArray.add(itemPoJo.getValue());
                        iterator.remove();
                        break;
                    }
                }
            }
            if (list.size() > BasicConstant.ONE){
                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235066, String.format(ImportErrorCodeEnum.API_ERROR_235066.getMsg(), fieldAttrEntity.getAttrName()));
            }
            jsonArray.addAll(list);
        } else {
            jsonArray.addAll(list);
        }
        if (jsonArray.isEmpty() && Objects.equals(fieldAttrEntity.getRequired(), 1)) {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235008, String.format(ImportErrorCodeEnum.API_ERROR_235008.getMsg(), fieldAttrEntity.getAttrName()));
        }
        formDataObj.put(fieldAttrEntity.getAttr(), jsonArray);
    }

    /**
     * format 简单产品格式（供应商供货产品）
     * @param dataJson
     * @param fieldAttr
     * @param attr
     * @param cellValue
     */
    public void formatSimpleProduct4Import(JSONObject dataJson, FieldAttrEntityForImport fieldAttr, String attr, Object cellValue) throws XbbException {
        JSONArray productList = new JSONArray();
        JSONObject productObject = new JSONObject();
        Map<String, Object> linkBusinessMap = fieldAttr.getLinkBusinessMap();
        if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
            // 17203 没有key会覆盖的时候会把原值塞进去，会报错。
            productObject.put(StringConstant.PRODUCT_LIST, productList);
            dataJson.put(attr, productObject);
            return;
        }
        try {
            List<String> singRowDataValues = Arrays.asList(cellValue.toString().split(StringConstant.COMMA));
            for (String value : singRowDataValues) {
                if (linkBusinessMap.containsKey(value)) {
                    JSONObject linkProductObj = new JSONObject();
                    linkProductObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, linkBusinessMap.get(value));
                    linkProductObj.put(StringConstant.BUSINESS_PRODUCT_ID, BasicConstant.ZERO);
                    linkProductObj.put(StringConstant.REDUNDANT_DATA, new JSONObject());
                    productList.add(linkProductObj);
                } else {
                    throw new XbbException(ImportErrorCodeEnum.API_ERROR_235008.getCode(), String.format(ImportErrorCodeEnum.API_ERROR_235008.getMsg(), fieldAttr.getAttrName()));
                }
            }
            productObject.put(StringConstant.PRODUCT_LIST, productList);
            dataJson.put(attr, productObject);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * format 供应商
     * @param dataJson
     * @param fieldAttrEntityForImport
     * @param attr
     * @param cellValue
     */
    public void formatSupplier4Import(JSONObject dataJson, FieldAttrEntityForImport fieldAttrEntityForImport, String attr, Object cellValue) throws XbbException{
        Map<String, Object> linkBusinessMap = fieldAttrEntityForImport.getLinkBusinessMap();
        JSONArray jsonArray = new JSONArray();
        if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
            return;
        }
        try {
            if (linkBusinessMap.containsKey(cellValue.toString())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, linkBusinessMap.get(cellValue.toString()));
                jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, cellValue);
                jsonArray.add(jsonObject);
            } else {
                throw new XbbException(SupplierContactErrorCodeEnum.API_ERROR_252008.getCode(), SupplierContactErrorCodeEnum.API_ERROR_252008.getMsg());
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        }
        dataJson.put(attr,jsonArray);
    }

    /**
     * format 下拉框
     * @param dataJson
     * @param fieldAttrEntityForImport
     * @param attr
     * @param cellValue
     */
    public void formatCombo4Import(JSONObject dataJson, FieldAttrEntityForImport fieldAttrEntityForImport, String attr, Object cellValue) {
        if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
            return;
        }
        dataJson.put(attr, cellValue);
        List<ItemPoJo> itemPoJoList = fieldAttrEntityForImport.getItems();
        for (ItemPoJo itemPoJo : itemPoJoList) {
            if (Objects.equals(cellValue.toString(), itemPoJo.getText())) {
                dataJson.put(attr, itemPoJo.getValue());
                break;
            }
        }
    }

    /**
     * format 关联单据
     * @param dataJson
     * @param refType
     * @param attr
     * @param cellValue
     * @param linkMap
     */
    public PaasFormDataEntityExt formatRefType4Import(JSONObject dataJson, String refType, String attr, Object cellValue, Map<String, Object> linkMap) throws XbbException{
        if (linkMap.containsKey(refType)) {
            JSONObject linkObject = (JSONObject) linkMap.get(refType);
            PaasFormDataEsListVO paasFormDataEsListVO = JSONObject.parseObject(linkObject.toJSONString(), PaasFormDataEsListVO.class);
            for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEsListVO.getPaasFormDataESList()) {
                if (Objects.equals(cellValue.toString(), paasFormDataEntityExt.getSerialNo())) {
                    JSONArray jsonArray = new JSONArray();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, paasFormDataEntityExt.getId());
                    jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, cellValue.toString());
                    jsonArray.add(jsonObject);
                    dataJson.put(attr, jsonArray);
                    return paasFormDataEntityExt;
                }
            }
            if (dataJson.get(attr) == null) {
                // TODO 关联单据不存在或已出入库
                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235010, ImportErrorCodeEnum.API_ERROR_235010.getMsg());
            }
        }
        return null;
    }

    /**
     * format 出入库仓库
     * @param dataJson
     * @param fieldAttrEntityForImport
     * @param attr
     * @param cellValue
     */
    public void formatWareHouse4Import(JSONObject dataJson, FieldAttrEntityForImport fieldAttrEntityForImport, String attr, Object cellValue) throws XbbException {
        try {
            if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                throw new XbbException(WarehouseErrorCodeEnum.API_ERROR_244016.getCode(), WarehouseErrorCodeEnum.API_ERROR_244016.getMsg());
            }
            List<ItemPoJo> itemPoJoList = fieldAttrEntityForImport.getItems();
            JSONArray jsonArray = new JSONArray();
            for (ItemPoJo itemPoJo : itemPoJoList) {
                if (Objects.equals(cellValue.toString(), itemPoJo.getText())) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, itemPoJo.getValue());
                    jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, itemPoJo.getText());
                    jsonObject.put(StringConstant.VALUE, itemPoJo.getText());
                    jsonArray.add(jsonObject);
                    break;
                }
            }
            if (jsonArray.isEmpty()) {
                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235008, String.format(ImportErrorCodeEnum.API_ERROR_235008.getMsg(), fieldAttrEntityForImport.getAttrName()));
            }
            dataJson.put(attr, jsonArray);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     *
     * @param titlePojoList 标题
     * @param fieldAttrEntityForImport 当前解释
     * @param parentTitle 父标题
     * @param subFieldAttrList 子解释列表
     * @param subFormCellValueList 子行数据
     * @param productJsonObject 产品对象
     */
    public void formatProduct4Import(List<CellTitlePojo> titlePojoList, FieldAttrEntityForImport fieldAttrEntityForImport, String parentTitle, List<FieldAttrEntityForImport> subFieldAttrList, List<CellValuePojo> subFormCellValueList, JSONObject productJsonObject) throws XbbException {
        // 编号中有所有子产品信息
        List<PaasFormDataEntityExt> temp = null;
        Double cost = 0D;
        Double price = 0D;
        try {
            for (FieldAttrEntityForImport subFormFieldAttr : subFieldAttrList) {
                String subAttrName = subFormFieldAttr.getAttrName();
                String subAttr = subFormFieldAttr.getAttr();
                String saasAttr = subFormFieldAttr.getSaasAttr();
                Integer subColumnIndex = getColumnIndexByTitle(titlePojoList, subAttrName, parentTitle);
                Object subFormCellValue = getValueByColumnIndex(subFormCellValueList, subColumnIndex);

                if (Objects.equals(subAttr, RelativeProductEnum.PRODUCT_NO.getAttr())) {
                    if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                        throw new XbbException(ProductErrorCodeEnum.API_ERROR_205036.getCode(), ProductErrorCodeEnum.API_ERROR_205036.getMsg());
                    }
                    productJsonObject.put(RelativeProductEnum.PRODUCT_NO.getSaasAttr(), subFormCellValue);
                    // TODO 如果解释中规格字段在编号字段前面会有问题。因为temp数据要在编号处获取，若果规格字段在前的话或导致temp数据还没有获取到。
                    temp = (List<PaasFormDataEntityExt>) fieldAttrEntityForImport.getLinkBusinessMap().get(subFormCellValue.toString());
                } else if (Objects.equals(subAttr, RelativeProductEnum.SPECIFICATION.getAttr())) {
                    Long productId = null;
                    Long parentId = null;
                    Double stock = null;
                    if(Objects.isNull(temp)) {
                        throw new XbbException(ImportErrorCodeEnum.API_ERROR_235016.getCode(), ImportErrorCodeEnum.API_ERROR_235016.getMsg());
                    }
                    for (PaasFormDataEntityExt paasFormDataEntityExt : temp) {
                        if (Objects.equals(paasFormDataEntityExt.getData().getInteger(ProductEnum.SPECIFICATION.getAttr()), 1)) {
                            if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                                throw new XbbException(ProductErrorCodeEnum.API_ERROR_205037.getCode(), ProductErrorCodeEnum.API_ERROR_205037.getMsg());
                            }
                            JSONObject value = null;
                            try {
                                value = JSONObject.parseObject(subFormCellValue.toString());
                            } catch (Exception e) {
                               throw new XbbException(ImportErrorCodeEnum.API_ERROR_235015, String.format(ImportErrorCodeEnum.API_ERROR_235015.getMsg(), RelativeProductEnum.SPECIFICATION.getAttrName()));
                            }
                            if (Objects.equals(paasFormDataEntityExt.getData().getJSONObject(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()), value)) {
                                productId = paasFormDataEntityExt.getId();
                                parentId = paasFormDataEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                                cost = paasFormDataEntityExt.getData().getDouble(ProductEnum.COST.getAttr());
                                price = paasFormDataEntityExt.getData().getDouble(ProductEnum.PRICE.getAttr());
                                stock = paasFormDataEntityExt.getData().getDouble(ProductEnum.STOCK.getAttr());
                                break;
                            }
                        } else {
                            if (Objects.equals(paasFormDataEntityExt.getData().getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()), Objects.toString(subFormCellValue, ""))) {
                                productId = paasFormDataEntityExt.getId();
                                parentId = paasFormDataEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                                cost = paasFormDataEntityExt.getData().getDouble(ProductEnum.COST.getAttr());
                                price = paasFormDataEntityExt.getData().getDouble(ProductEnum.PRICE.getAttr());
                                stock = paasFormDataEntityExt.getData().getDouble(ProductEnum.STOCK.getAttr());
                                break;
                            }
                        }
                    }
                    if(Objects.isNull(productId)) {
                        throw new XbbException(ImportErrorCodeEnum.API_ERROR_235016.getCode(), ImportErrorCodeEnum.API_ERROR_235016.getMsg());
                    }
                    productJsonObject.put(RelativeProductEnum.SPECIFICATION.getSaasAttr(), subFormCellValue);
                    productJsonObject.put(ProductEnum.PARENT_ID.getSaasAttr(), parentId);
                    productJsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, productId);
                    // 单价
                    productJsonObject.put(RelativeProductEnum.PRODUCT_PRICE.getSaasAttr(), price);
                    // 盘点单需要
                    //productJsonObject.put(StringConstant.ORI_NUM, stock);
                } else if (Objects.equals(subAttr, RelativeProductEnum.NUM.getAttr())) {
                    if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                        throw new XbbException(ProductErrorCodeEnum.API_ERROR_205039.getCode(), ProductErrorCodeEnum.API_ERROR_205039.getMsg());
                    }
                    productJsonObject.put(RelativeProductEnum.NUM.getSaasAttr(), subFormCellValue.toString());
                } else if (Objects.equals(subAttr, RelativeProductEnum.WAREHOUSE.getAttr())) {
                    if ((Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString()))
                            && Objects.equals(subFormFieldAttr.getRequired(), 1)) {
                        throw new XbbException(WarehouseErrorCodeEnum.API_ERROR_244016.getCode(), WarehouseErrorCodeEnum.API_ERROR_244016.getMsg());
                    }
                    List<ItemPoJo> itemPoJoList = subFormFieldAttr.getItems();
                    for (ItemPoJo itemPoJo : itemPoJoList) {
                        if (Objects.equals(Objects.toString(subFormCellValue, ""), itemPoJo.getText())) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, itemPoJo.getValue());
                            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, itemPoJo.getText());
                            jsonObject.put(StringConstant.VALUE, itemPoJo.getText());
                            productJsonObject.put(RelativeProductEnum.WAREHOUSE.getSaasAttr(), jsonObject);
                            break;
                        }
                    }
                    if (Objects.isNull(productJsonObject.get(RelativeProductEnum.WAREHOUSE.getSaasAttr()))) {
                        throw new XbbException(ImportErrorCodeEnum.API_ERROR_235008.getCode(), String.format(ImportErrorCodeEnum.API_ERROR_235008.getMsg(), RelativeProductEnum.WAREHOUSE.getAttrName()));
                    }
                } else if (Objects.equals(subAttr, RelativeProductEnum.COST.getAttr())) {
                    // 鬼晓得哪个单据用哪个，一起传了 入库自己填，出库不用填，我也很绝望啊
                    if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                        productJsonObject.put(saasAttr, 0D);
                        productJsonObject.put("productCost", 0D);
                    } else {
                        productJsonObject.put(saasAttr, subFormCellValue);
                        productJsonObject.put("productCost", subFormCellValue);
                    }
                } else {
                    productJsonObject.put(saasAttr, subFormCellValue);
                }
            }
            if (!productJsonObject.containsKey("productCost")) {
                // 鬼晓得哪个单据用哪个，一起传了
                productJsonObject.put("cost", cost);
                productJsonObject.put("productCost", cost);
                productJsonObject.put("estimateCost", cost);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     *
     * @param titlePojoList 标题
     * @param subFormCellValueList 子行数据
     * @param productJsonObject 产品对象
     * @param stockParentTitle 库存产品父标题
     * @param stockSubFieldAttrList 库存产品解释
     */
    public void formatStockProduct4Import(List<CellTitlePojo> titlePojoList, List<CellValuePojo> subFormCellValueList, JSONObject productJsonObject, String stockParentTitle, List<FieldAttrEntityForImport> stockSubFieldAttrList) throws XbbException {
        try {
            for (FieldAttrEntityForImport subFormFieldAttr : stockSubFieldAttrList) {
                String subAttrName = subFormFieldAttr.getAttrName();
                Integer subColumnIndex = getColumnIndexByTitle(titlePojoList, subAttrName, stockParentTitle);
                Object subFormCellValue = getValueByColumnIndex(subFormCellValueList, subColumnIndex);
                if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                    continue;
                }
                if (Objects.equals(subFormFieldAttr.getAttr(), StockProductEnum.PRODUCE_DATE.getAttr())) {
                    //校验 库存^生产日期
                    /*if(!StringUtil.regularDate(subFormCellValue.toString())) {
                        throw new XbbException(ErrorCodeEnum.API_ERROR_235025,"生产日期格式错误！");
                    }*/
                    Long time = DateTimeUtil.getExcelTime(subFormCellValue.toString());
                    if (time == 0L) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.FORMAT_INVALID, subFormFieldAttr.getAttrName());
                    }
                    subFormCellValue = DateTimeUtil.getStringEpochSecond(time, DateTimeUtil.SDFDate);
                }
                productJsonObject.put(subFormFieldAttr.getSaasAttr(), subFormCellValue);
            }
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * format负责人
     * @param formDataAddDTO
     * @param fieldAttrEntityForImport
     * @param cellValue
     * @throws XbbException
     */
    public void formatOwnId4Import(FormDataAddDTO formDataAddDTO, FieldAttrEntityForImport fieldAttrEntityForImport, Object cellValue) throws XbbException {
        try {
            if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                throw new XbbException(WarehouseErrorCodeEnum.API_ERROR_244012.getCode(), WarehouseErrorCodeEnum.API_ERROR_244012.getMsg());
            }
            Map<String, Object> userMap = fieldAttrEntityForImport.getLinkBusinessMap();
            for (Map.Entry<String, Object> entry: userMap.entrySet()) {
                if (Objects.equals(cellValue.toString(), entry.getKey())) {
                    ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                    returnUserAndDepartmentPojo.setId(entry.getValue());
                    formDataAddDTO.setOwnerId(Collections.singletonList(returnUserAndDepartmentPojo));
                    break;
                }
            }
            if (Objects.equals(fieldAttrEntityForImport.getRequired(), 1) && formDataAddDTO.getOwnerId() == null) {
                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235008.getCode(), String.format(ImportErrorCodeEnum.API_ERROR_235008.getMsg(), fieldAttrEntityForImport.getAttrName()));
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 格式化有关联业务类型的数据
     *
     * @param linkCustomerId
     * @param dataJson
     * @param fieldAttr
     * @param cellValue
     * @param selectAttr
     * @throws XbbException
     */
    public Long formatRelyBusiness(Long linkCustomerId, JSONObject dataJson, FieldAttrEntityForImport fieldAttr, Object cellValue, String selectAttr) throws XbbException {
        Map<String, Object> linkBusinessMap = fieldAttr.getLinkBusinessMap();
        List<String> singRowDataValues = Arrays.asList(cellValue.toString().split(StringConstant.COMMA));
        PaasFormDataEntityExt realBusinessEntity = null;
        for (String value : singRowDataValues) {
            List<PaasFormDataEntityExt> businessList = (List<PaasFormDataEntityExt>)linkBusinessMap.get(value);
            if (Objects.isNull(businessList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_EXISTS_IN_SYSTEM_OR_NOT_SUP, fieldAttr.getAttrName(), fieldAttr.getAttrName());
            }

            for (PaasFormDataEntityExt paasFormDataEntityExt : businessList) {
                Long businessCustomerId = paasFormDataEntityExt.getData().getLong(selectAttr);
                if (Objects.equals(linkCustomerId, businessCustomerId)) {
                    realBusinessEntity = paasFormDataEntityExt;
                    break;
                }
            }
            if (Objects.isNull(realBusinessEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_RELY_BUINESS, fieldAttr.getAttrName());
            }
            Map<String, Object> tempLinkBusinessMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            tempLinkBusinessMap.put(value, realBusinessEntity.getId());
            fieldAttr.setTempLinkBusinessMap(tempLinkBusinessMap);
            formatLinkBusinessValue4Import(dataJson, fieldAttr, value);
        }

        return Objects.isNull(realBusinessEntity) ? 0L :realBusinessEntity.getId();
    }

    /**
     * 格式化有关联业务类型的数据
     *
     * @param linkDataId
     * @param dataJson
     * @param fieldAttr
     * @param cellValue
     * @param selectAttr
     * @throws XbbException
     */
    public List<PaasFormDataEntityExt> formatMultiRelyBusiness(Long linkDataId, JSONObject dataJson, FieldAttrEntityForImport fieldAttr, Object cellValue, String selectAttr) throws XbbException {
        Map<String, Object> linkBusinessMap = fieldAttr.getLinkBusinessMap();
        cellValue = cellValue.toString().replaceAll(StringConstant.CHINESE_COMMA, StringConstant.COMMA);
        String[] cellArr = cellValue.toString().split(StringConstant.COMMA);
        List<PaasFormDataEntityExt> businessEntityList = new ArrayList<>();
        JSONArray businessIdList = new JSONArray();
        for (int i = 0; i < cellArr.length; i ++) {
            JSONObject jsonObject = new JSONObject();
            List<PaasFormDataEntityExt> businessList = (List<PaasFormDataEntityExt>)linkBusinessMap.get(cellArr[i]);
            if (Objects.isNull(businessList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_EXISTS_IN_SYSTEM_OR_NOT_SUP, fieldAttr.getAttrName(), fieldAttr.getAttrName());
            }
            PaasFormDataEntityExt realBusinessEntity = null;
            outter:
            for (PaasFormDataEntityExt paasFormDataEntityExt : businessList) {
                if (paasFormDataEntityExt.getData().get(selectAttr) != null) {
                    if (paasFormDataEntityExt.getData().get(selectAttr) instanceof List) {
                        JSONArray businessCustomerIdList = paasFormDataEntityExt.getData().getJSONArray(selectAttr);
                        for (Object o : businessCustomerIdList) {
                            Long businessCustomerId = Long.valueOf(o.toString());
                            if (Objects.equals(linkDataId, businessCustomerId)) {
                                realBusinessEntity = paasFormDataEntityExt;
                                break outter;
                            }
                        }
                    } else {
                        Long businessCustomerId = paasFormDataEntityExt.getData().getLong(selectAttr);
                        if (Objects.equals(linkDataId, businessCustomerId)) {
                            realBusinessEntity = paasFormDataEntityExt;
                            break;
                        }
                    }
                }
            }
            if (Objects.isNull(realBusinessEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.HAVE_SAME_NAME_IN_SYSTEM, fieldAttr.getAttrName());
            }
            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, realBusinessEntity.getId());
            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, cellArr[i]);
            businessIdList.add(jsonObject);
            businessEntityList.add(realBusinessEntity);
        }
        dataJson.put(fieldAttr.getAttr(), businessIdList.toArray());
        return businessEntityList;
    }

    public Object removeDuplicatesCellValue(Object cellValue){
        List<String> list = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        cellValue = cellValue.toString().replaceAll(StringConstant.CHINESE_COMMA, StringConstant.COMMA);
        String[] cellArr = cellValue.toString().split(StringConstant.COMMA);
        for (int i = 0; i < cellArr.length; i ++) {
            if(!list.contains(cellArr[i])){
                list.add(cellArr[i]);
                stringBuilder.append(cellArr[i]+StringConstant.COMMA);
            }
        }
        stringBuilder.deleteCharAt(stringBuilder.length()-1);
        return stringBuilder.toString();
    }

    /**
     * 格式化有发票关联业务类型的数据
     *
     * @param linkIdIn 关联idIn
     * @param dataJson
     * @param fieldAttr
     * @param cellValue
     * @param selectAttr
     * @throws XbbException
     */
    public List<PaasFormDataEntityExt> formatInvoiceMultiRelyBusiness(List<Long> linkIdIn, JSONObject dataJson, FieldAttrEntityForImport fieldAttr, Object cellValue, String selectAttr) throws XbbException {
        Map<String, Object> linkBusinessMap = fieldAttr.getLinkBusinessMap();
        String[] cellArr = cellValue.toString().split(StringConstant.COMMA);
        List<PaasFormDataEntityExt> businessEntityList = new ArrayList<>();
        Set<Long> refMapping = new HashSet<>();
        JSONArray businessIdList = new JSONArray();
        for (int i = 0; i < cellArr.length; i ++) {
            JSONObject jsonObject = new JSONObject();
            List<PaasFormDataEntityExt> businessList = (List<PaasFormDataEntityExt>)linkBusinessMap.get(cellArr[i]);
            if (Objects.isNull(businessList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_EXISTS_IN_SYSTEM_OR_NOT_SUP, fieldAttr.getAttrName(), fieldAttr.getAttrName());
            }
            List<PaasFormDataEntityExt> realBusinessEntityList = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEntityExt : businessList) {
                if (paasFormDataEntityExt.getData().get(selectAttr) != null) {
                    if (paasFormDataEntityExt.getData().get(selectAttr) instanceof List) {
                        JSONArray businessRefIdList = paasFormDataEntityExt.getData().getJSONArray(selectAttr);
                        //通过合同id 和 关联id 查询出来的实体 取他的关联在验证是否是上游的
                        for (Object o : businessRefIdList) {
                            //确定在合同下的关联的合同id
                            Long businessRefId = Long.valueOf(o.toString());
                            if(linkIdIn.contains(businessRefId)){
                                refMapping.add(businessRefId);
                                //如果回款单 或者付款单 关联了两个合同
                                if(!realBusinessEntityList.contains(paasFormDataEntityExt)){
                                    realBusinessEntityList.add(paasFormDataEntityExt);
                                }
                            }
                        }
                    } else {
                        Long businessRefId = paasFormDataEntityExt.getData().getLong(selectAttr);
                        if(linkIdIn.contains(businessRefId)){
                            realBusinessEntityList.add(paasFormDataEntityExt);
                            refMapping.add(businessRefId);
                            break;
                        }
                    }
                }
            }
            if (CollectionsUtil.isEmpty(realBusinessEntityList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_EXISTS_IN_SYSTEM_OR_NOT_SUP, fieldAttr.getAttrName(),fieldAttr.getAttrName());
            }

            if (CollectionsUtil.isNotEmpty(realBusinessEntityList)) {
                for (PaasFormDataEntityExt paasFormDataEntityExt : realBusinessEntityList) {
                    jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, paasFormDataEntityExt.getId());
                    jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, cellArr[i]);
                }
            }
            businessIdList.add(jsonObject);
            businessEntityList.addAll(realBusinessEntityList);
        }
        if(CollectionsUtil.isNotEmpty(linkIdIn)){
            if(!Objects.equals(refMapping.size(),linkIdIn.size())){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_RELY_BUINESS_NOT_UNDER);
            }
        }
        dataJson.put(fieldAttr.getAttr(), businessIdList.toArray());
        return businessEntityList;
    }

    /**
     * 检查发票的上游业务
     *
     * @param linkIdIn 关联idIn
     * @param fieldAttr
     * @param cellValue
     * @param selectAttr
     * @throws XbbException
     */
    public void checkInvoiceMultiRelyBusiness(List<Long> linkIdIn,FieldAttrEntityForImport fieldAttr, Object cellValue, String selectAttr) throws XbbException {
        Map<String, Object> linkBusinessMap = fieldAttr.getLinkBusinessMap();
        String[] cellArr = cellValue.toString().split(StringConstant.COMMA);
        Set<Long> refMapping = new HashSet<>();
        for (int i = 0; i < cellArr.length; i ++) {
            List<PaasFormDataEntityExt> businessList = (List<PaasFormDataEntityExt>)linkBusinessMap.get(cellArr[i]);
            if (Objects.isNull(businessList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_EXISTS_IN_SYSTEM_OR_NOT_SUP, fieldAttr.getAttrName(), fieldAttr.getAttrName());
            }
            List<PaasFormDataEntityExt> realBusinessEntityList = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEntityExt : businessList) {
                if (paasFormDataEntityExt.getData().get(selectAttr) != null) {
                    if (paasFormDataEntityExt.getData().get(selectAttr) instanceof List) {
                        JSONArray businessRefIdList = paasFormDataEntityExt.getData().getJSONArray(selectAttr);
                        //通过合同id 和 关联id 查询出来的实体 取他的关联在验证是否是上游的
                        for (Object o : businessRefIdList) {
                            //确定在合同下的关联的合同id
                            Long businessRefId = Long.valueOf(o.toString());
                            if(linkIdIn.contains(businessRefId)){
                                if(!realBusinessEntityList.contains(paasFormDataEntityExt)){
                                    realBusinessEntityList.add(paasFormDataEntityExt);
                                    refMapping.add(businessRefId);
                                }
                            }
                        }
                    } else {
                        Long businessRefId = paasFormDataEntityExt.getData().getLong(selectAttr);
                        if(linkIdIn.contains(businessRefId)){
                            realBusinessEntityList.add(paasFormDataEntityExt);
                            refMapping.add(businessRefId);
                            break;
                        }
                    }
                }
            }
            if (CollectionsUtil.isEmpty(realBusinessEntityList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_EXISTS_IN_SYSTEM_OR_NOT_SUP, fieldAttr.getAttrName(),fieldAttr.getAttrName());
            }
        }
        if(CollectionsUtil.isNotEmpty(linkIdIn)){
            if(!Objects.equals(refMapping.size(),linkIdIn.size())){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_RELY_BUINESS_NOT_UNDER);
            }
        }
    }

    /**
     * 格式化一般的产品
     *
     * @param titlePojoList
     * @param dataJson
     * @param rowValueList
     * @param fieldAttr
     * @throws XbbException
     */
    public void formatCommonProduct(List<CellTitlePojo> titlePojoList, JSONObject dataJson, List<List<CellValuePojo>> rowValueList, FieldAttrEntityForImport fieldAttr, Integer businessType, String corpid) throws XbbException {
        // 产品解释
        String parentTitle = fieldAttr.getAttrName();
        SubFormPoJo subFormPoJo = fieldAttr.getSubForm();
        List<? extends FieldAttrEntity> items = subFormPoJo.getItems();
        List<FieldAttrEntityForImport> subFieldAttrList = new ArrayList<>();
        //fix bug 38716
        for(FieldAttrEntity fieldAttrEntity :  items){
            FieldAttrEntityForImport fieldAttrEntityForImport =  JSON.parseObject(JSON.toJSONString(fieldAttrEntity),FieldAttrEntityForImport.class);
            subFieldAttrList.add(fieldAttrEntityForImport);
        }
//        List<FieldAttrEntityForImport> subFieldAttrList = JSON.parseArray(JSON.toJSONString(subFormPoJo.getItems()), FieldAttrEntityForImport.class);
        // 获取产品array
        JSONArray productJsonArray = new JSONArray();
        // 产品开始--结束索引
        String subFormFirstColumnTitle = subFieldAttrList.get(0).getAttrName();
        Integer subFormFirstColumnIndex = getColumnIndexByTitle(titlePojoList, subFormFirstColumnTitle, parentTitle);
        Integer subFormLastColumnIndex = subFormFirstColumnIndex + subFieldAttrList.size();

        // 产品可以分行，需要遍历所有行
        CellValuePojo cellValuePojo;
        StringBuilder errorStringList = new StringBuilder();
        for (List<CellValuePojo> subFormCellValueList : rowValueList) {
            boolean isEmptyRow = true;
            for (int i=subFormFirstColumnIndex; i<subFormLastColumnIndex; i++) {
                cellValuePojo = subFormCellValueList.get(i);
                if (!StringUtil.isEmpty(Objects.toString(cellValuePojo.getValue(), ""))) {
                    isEmptyRow = false;
                    break;
                }
            }
            if (isEmptyRow) {
                continue;
            }
            // 产品
            JSONObject productJsonObject = new JSONObject();
            String errorString = formatNewProduct4Import(titlePojoList, fieldAttr, fieldAttr.getAttrName(), subFieldAttrList, subFormCellValueList, productJsonObject, businessType, corpid);
            if (StringUtil.isNotEmpty(errorString)) {
                if (errorStringList.length() == 0) {
                    errorStringList.append(errorString);
                } else {
                    errorStringList.append("，").append(errorString);
                }
                continue;
            }
            // BOM成品数量默认为1，不用填
            if (Objects.equals(businessType, XbbRefTypeEnum.BOM_BILL.getCode()) && Objects.equals(fieldAttr.getAttr(), BomBillEnum.PRODUCT.getAttr())) {
                productJsonObject.put(SelectProductEnum.NUM.getAttr(), 1);
            }
            if (productJsonObject.containsKey(SelectProductEnum.DISCOUNT.getAttr())) {
                Double price = productJsonObject.getDouble(SelectProductEnum.PRICE.getAttr());
                Double sellPrice = productJsonObject.getDouble(SelectProductEnum.SELLING_PRICE.getAttr());
                if (Objects.nonNull(price) && !Objects.equals(price, 0D) && Objects.nonNull(sellPrice)) {
                    productJsonObject.put(SelectProductEnum.DISCOUNT.getAttr(), Arith.div(sellPrice, price) * 100);
                }
            }
            productJsonArray.add(productJsonObject);
        }
        if (errorStringList.length() > 0) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), errorStringList.toString());
        }
        // 需要添加成本，成本小计，库存数量
        List<Integer> hasStockInfo = Arrays.asList(XbbRefTypeEnum.ASSEMBLE.getCode(), XbbRefTypeEnum.OTHER_INSTOCK.getCode(), XbbRefTypeEnum.PURCHASE_INSTOCK.getCode(),
                XbbRefTypeEnum.OTHER_OUTSTOCK.getCode(), XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode());
        if (hasStockInfo.contains(businessType)) {
            putStockInfoToProduct(productJsonArray, corpid, fieldAttr, businessType);
        }
        dataJson.put(fieldAttr.getAttr(), productJsonArray);
    }

    private void putStockInfoToProduct(JSONArray productJsonArray, String corpid, FieldAttrEntityForImport fieldAttr, Integer businessType) throws XbbException {
        Set<Long> warehouseIdList = new HashSet<>();
        Set<Long> productIdList = new HashSet<>();
        Set<String> batchKeyList = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (int i = 0; i < productJsonArray.size(); i++) {
            JSONObject jsonObject = productJsonArray.getJSONObject(i);
            Long productId = jsonObject.getJSONObject(SelectProductEnum.PRODUCT.getAttr()).getLong(StringConstant.DATA_ID);
            Long warehouseId = jsonObject.getJSONArray(SelectProductEnum.WAREHOUSE.getAttr()).getJSONObject(0).getLong(StringConstant.DATA_ID);
            String batch = jsonObject.getString(SelectProductEnum.BATCH.getAttr());
            Long produceDate = jsonObject.getLong(SelectProductEnum.PRODUCE_DATE.getAttr()) == null ? 0L : jsonObject.getLong(SelectProductEnum.PRODUCE_DATE.getAttr());
            Long guaranteePeriod = jsonObject.getLong(SelectProductEnum.GUARANTEE_PERIOD.getAttr()) == null ? 0L : jsonObject.getLong(SelectProductEnum.GUARANTEE_PERIOD.getAttr());
            StringBuilder sb;
            if (StringUtil.isNotEmpty(batch)) {
                sb = new StringBuilder();
                sb.append(productId).append(StringConstant.CROSS).append(warehouseId).append(StringConstant.CROSS).append(batch).append(StringConstant.CROSS).append(produceDate).append(StringConstant.CROSS).append(guaranteePeriod * TimeConstant.SECONDS_PER_DAY);
                batchKeyList.add(sb.toString());
            }
            warehouseIdList.add(warehouseId);
            productIdList.add(productId);
        }
        Map<String, ProductStockEntity> productBatchWarehouseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (!batchKeyList.isEmpty()) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery(ProductStockSubFormEnum.getEsAttr(ProductStockSubFormEnum.BATCH_KEY), batchKeyList));
            boolQueryBuilder.filter(termQuery(ProductStockSubFormEnum.getEsAttr(ProductStockSubFormEnum.WAREHOUSE_CHECKED),1));
            List<PaasFormDataEntity> productStockEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT_STOCK_INFO,boolQueryBuilder,PaasFormDataEntity.class,null);
            List<ProductStockEntity> productStockEntities = transferSubFormHelper.transferFormDataToProductStockList(productStockEntityList);
            productStockEntities.forEach(item -> {
                productBatchWarehouseMap.put(item.getBatchKey(), item);
            });
        }
        Map<String, ProductWarehouseEntity> productWarehouseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (!productIdList.isEmpty() && !warehouseIdList.isEmpty()) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.PRODUCT_ID), productIdList));
            boolQueryBuilder.filter(termsQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.WAREHOUSE_ID), warehouseIdList));
            // 仓库库存表有全仓数据，不要查出来
            boolQueryBuilder.mustNot(termQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.WAREHOUSE_ID), 0L));
            boolQueryBuilder.filter(termQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.WAREHOUSE_CHECKED), 1));
            List<PaasFormDataEntity> list = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT_WAREHOUSE, boolQueryBuilder, PaasFormDataEntity.class, Arrays.asList(ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.PRODUCT_ID), ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.WAREHOUSE_ID), ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.NUM), ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.COST), ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.WAREHOUSE_NAME)));
            List<ProductWarehouseEntity> productWarehouseEntities = transferSubFormHelper.transferFormDataToProductWarehouseList(list);
            productWarehouseEntities.forEach(item -> {
                String key = item.getProductId() + "_" + item.getWarehouseId();
                productWarehouseMap.put(key, item);
            });
        }
        boolean isAssembleOutProduct = Objects.equals(businessType, XbbRefTypeEnum.ASSEMBLE.getCode()) && Objects.equals(fieldAttr.getAttr(), AssembleEnum.OUT_PRODUCTS.getAttr());
        boolean isOutstockProduct = (Objects.equals(businessType, XbbRefTypeEnum.OTHER_OUTSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())) && Objects.equals(fieldAttr.getAttr(), OutstockEnum.PRODUCT.getAttr());
        StringBuilder sb;
        for (int i = 0; i < productJsonArray.size(); i++) {
            JSONObject jsonObject = productJsonArray.getJSONObject(i);
            Long productId = jsonObject.getJSONObject(SelectProductEnum.PRODUCT.getAttr()).getLong(StringConstant.DATA_ID);
            Long warehouseId = jsonObject.getJSONArray(SelectProductEnum.WAREHOUSE.getAttr()).getJSONObject(0).getLong(StringConstant.DATA_ID);
            String batch = jsonObject.getString(SelectProductEnum.BATCH.getAttr());
            Double cost = jsonObject.getDouble(SelectProductEnum.COST.getAttr());
            Double num = jsonObject.getDouble(SelectProductEnum.NUM.getAttr());
            if (StringUtil.isNotEmpty(batch) && (isAssembleOutProduct || isOutstockProduct)) {
                Long produceDate = jsonObject.getLong(SelectProductEnum.PRODUCE_DATE.getAttr()) == null ? 0L : jsonObject.getLong(SelectProductEnum.PRODUCE_DATE.getAttr());
                Long guaranteePeriod = jsonObject.getLong(SelectProductEnum.GUARANTEE_PERIOD.getAttr()) == null ? 0L : jsonObject.getLong(SelectProductEnum.GUARANTEE_PERIOD.getAttr());
                sb = new StringBuilder();
                String key = sb.append(productId).append(StringConstant.CROSS).append(warehouseId).append(StringConstant.CROSS).append(batch).append(StringConstant.CROSS).append(produceDate).append(StringConstant.CROSS).append(guaranteePeriod * TimeConstant.SECONDS_PER_DAY).toString();
                if (productBatchWarehouseMap.containsKey(key)) {
                    cost = productBatchWarehouseMap.get(key).getCost() == null ? 0D :  productBatchWarehouseMap.get(key).getCost();
                    jsonObject.put(SelectProductEnum.COST.getAttr(), cost);
                    jsonObject.put(SelectProductEnum.TOTAL_COST.getAttr(), Arith.mul(cost, num));
                    jsonObject.put(SelectProductEnum.STOCK.getAttr(), productBatchWarehouseMap.get(key).getNum());
                    if (Objects.nonNull(productBatchWarehouseMap.get(key).getGuaranteePeriod())) {
                        jsonObject.put(SelectProductEnum.GUARANTEE_PERIOD.getAttr(), Arith.div(productBatchWarehouseMap.get(key).getGuaranteePeriod(), 86400));
                    }
                    jsonObject.put(SelectProductEnum.PRODUCE_DATE.getAttr(), productBatchWarehouseMap.get(key).getProduceDate());
                } else {
                    throw new XbbException(OutstockErrorCodeEnum.API_ERROR_212026);
                }
            } else if (isAssembleOutProduct || isOutstockProduct){
                String key = productId + "_" + warehouseId;
                if (productWarehouseMap.containsKey(key)) {
                    cost = productWarehouseMap.get(key).getCost() == null ? 0D :  productWarehouseMap.get(key).getCost();
                    jsonObject.put(SelectProductEnum.COST.getAttr(), cost);
                    jsonObject.put(SelectProductEnum.TOTAL_COST.getAttr(), Arith.mul(cost, num));
                    jsonObject.put(SelectProductEnum.STOCK.getAttr(), productWarehouseMap.get(key).getNum());
                } else {
                    // 没有关联仓库需要用产品的成本
                    jsonObject.put(SelectProductEnum.TOTAL_COST.getAttr(), Arith.mul(cost, num));
                    jsonObject.put(SelectProductEnum.STOCK.getAttr(), 0);
                }
            }
        }

    }

    public String formatNewProduct4Import(List<CellTitlePojo> titlePojoList, FieldAttrEntityForImport fieldAttrEntityForImport, String parentTitle, List<FieldAttrEntityForImport> subFieldAttrList, List<CellValuePojo> subFormCellValueList, JSONObject productJsonObject, Integer businessType, String corpid) throws XbbException {
        // 编号中有所有子产品信息
        List<PaasFormDataEntityExt> temp = null;
        Double price = null;
        // 冗余放入成本
        Double cost = null;
        Object unit = null;
        Double stock = null;
        StringBuilder errorString = new StringBuilder();
        //保质期天数
        Object sheflifeDays = null;

        //单价
        List<Integer> hasPriceList = Arrays.asList(XbbRefTypeEnum.CONTRACT.getCode(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), XbbRefTypeEnum.QUOTATION.getCode(),
                XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode(), XbbRefTypeEnum.WORK_ORDER_V2.getCode());
        //售价小计
        List<Integer> hasSellPriceTotalList = Arrays.asList(XbbRefTypeEnum.CONTRACT.getCode(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(),
                XbbRefTypeEnum.QUOTATION.getCode(), XbbRefTypeEnum.WORK_ORDER_V2.getCode());
        //单价小计
        List<Integer> hasPriceTotalList = Arrays.asList(XbbRefTypeEnum.REFUND.getCode(), XbbRefTypeEnum.PURCHASE.getCode());
        // 成本小计
        List<Integer> hasCostTotalList = Collections.singletonList(XbbRefTypeEnum.PURCHASE.getCode());
        // 库存数量
        List<Integer> hasStockList = Collections.singletonList(XbbRefTypeEnum.PRODUCTION_ORDER.getCode());
        //需要单独添加price
        boolean hasAddPrice = Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode());
        // parent_id
        boolean hasParentId = Objects.equals(businessType, XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode());
        try {
            Object productNo = null;
            for (FieldAttrEntityForImport forImport : subFieldAttrList) {
                String subAttr = forImport.getAttr();
                if (Objects.equals(subAttr, SelectProductEnum.PRODUCT_NO.getAttr())) {
                    String subAttrName = forImport.getAttrName();
                    Integer subColumnIndex = getColumnIndexByTitle(titlePojoList, subAttrName, parentTitle);
                    Object subFormCellValue = getValueByColumnIndex(subFormCellValueList, subColumnIndex);
                    productNo = subFormCellValue;

                    temp = (List<PaasFormDataEntityExt>) fieldAttrEntityForImport.getLinkBusinessMap().get(subFormCellValue.toString());

                    break;
                }
            }
            Map<Long, List<ProductUnitPriceEntity>> productUnitPriceEntityMap = fieldAttrEntityForImport.getProductUnitPriceEntityMap();
            Map<String, MultiUnitItemPoJo> groupBaseUnitMap = fieldAttrEntityForImport.getGroupBaseUnitMap();
            Object batchNo = null;
            //excel中输入的单位
            Object unitText = null;
            //业务单位数量
            Double businessUnitNum = null;
            for (FieldAttrEntityForImport forImport : subFieldAttrList) {
                String subAttr = forImport.getAttr();
                if(Objects.equals(subAttr, ProductEnum.SPECIFICATION.getAttr())){
                    String subAttrName = forImport.getAttrName();
                    Integer subColumnIndex = getColumnIndexByTitle(titlePojoList, subAttrName, parentTitle);
                    batchNo = getValueByColumnIndex(subFormCellValueList, subColumnIndex);
                }else if(Objects.equals(subAttr, ProductEnum.UNIT.getAttr())){
                    String subAttrName = forImport.getAttrName();
                    Integer subColumnIndex = getColumnIndexByTitle(titlePojoList, subAttrName, parentTitle);
                    unitText = getValueByColumnIndex(subFormCellValueList, subColumnIndex);
                }else if(Objects.equals(SelectProductEnum.NUM.getAttr(),subAttr)){
                    String subAttrName = forImport.getAttrName();
                    Integer subColumnIndex = getColumnIndexByTitle(titlePojoList, subAttrName, parentTitle);
                    Object subFormCellValue = getValueByColumnIndex(subFormCellValueList, subColumnIndex);
                    if (Objects.nonNull(subFormCellValue) && StringUtil.isDigital(subFormCellValue.toString())){
                        businessUnitNum = Double.valueOf(subFormCellValue.toString());
                    }
                }
            }
            Outter:
            for (FieldAttrEntityForImport subFormFieldAttr : subFieldAttrList) {
                String subAttrName = subFormFieldAttr.getAttrName();
                String subAttr = subFormFieldAttr.getAttr();
                boolean isSystemField = Objects.equals(subFormFieldAttr.getIsRedundant(), 0);
                Integer subColumnIndex = getColumnIndexByTitle(titlePojoList, subAttrName, parentTitle);
                Object subFormCellValue = getValueByColumnIndex(subFormCellValueList, subColumnIndex);
                if (Objects.equals(subAttr, SelectProductEnum.PRODUCT_NO.getAttr())) {
                    if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                        errorString.append(ProductErrorCodeEnum.API_ERROR_205036.getMsg()).append("(").append(productNo).append(")");
                        break Outter;
                    }
                } else if (Objects.equals(subAttr, SelectProductEnum.SPECIFICATION.getAttr())) {
                    Long productId = null;
                    Long parentId = null;
                    if (Objects.isNull(temp)) {
                        errorString.append(ImportErrorCodeEnum.API_ERROR_235034.getMsg()).append("(").append(productNo).append(")");
                        break Outter;
                    }
                    for (PaasFormDataEntityExt paasFormDataEntityExt : temp) {
                        if (Objects.equals(paasFormDataEntityExt.getData().getInteger(ProductEnum.SPECIFICATION.getAttr()), 1)) {
                            if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                                errorString.append(ProductErrorCodeEnum.API_ERROR_205037.getMsg()).append("(").append(productNo).append(")");
                                break Outter;
                            }
                            JSONObject value;
                            try {
                                value = JSONObject.parseObject(subFormCellValue.toString());
                            } catch (Exception e) {
                                errorString.append(String.format(ImportErrorCodeEnum.API_ERROR_235015.getMsg(), subAttrName)).append("(").append(productNo).append(")");
                                break Outter;
                            }
                            if (Objects.equals(paasFormDataEntityExt.getData().getJSONObject(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()), value)) {
                                productId = paasFormDataEntityExt.getId();
                                parentId = paasFormDataEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                                price = paasFormDataEntityExt.getData().getDouble(ProductEnum.PRICE.getAttr());
                                cost = paasFormDataEntityExt.getData().getDouble(ProductEnum.COST.getAttr());
                                //多单位产品 单位的value为业务单位对应的value
                                if (Objects.equals(BasicConstant.ONE,paasFormDataEntityExt.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr())) && !StockConstant.IMPORT_MULTI_UNIT_TYPE.contains(businessType)){
                                    Long unitGroupId = paasFormDataEntityExt.getData().getLong(ProductEnum.UNIT.getAttr());
                                    MultiUnitItemPoJo groupMessage = groupBaseUnitMap.getOrDefault(Objects.toString(unitGroupId, ""), new MultiUnitItemPoJo());
                                    List<String> unitTextList = new ArrayList<>();
                                    UnitItemPoJo businessUnitItemPoJo = null;
                                    for (UnitItemPoJo unitItemPoJo : groupMessage.getItemDataPoJoList()) {
                                        unitTextList.add(unitItemPoJo.getText());
                                    }
                                    // 多单位产品  业务单据导入单位不填 或者填写单位不是单位组中的业务单位  默认给基本单位
                                    if (Objects.isNull(unitText) || StringUtil.isEmpty(unitText.toString()) || !unitTextList.contains(unitText)){
                                       unitText = groupMessage.getBaseName();
                                    }
                                    for (UnitItemPoJo unitItemPoJo : groupMessage.getItemDataPoJoList()) {
                                        if (Objects.equals(unitItemPoJo.getText(), unitText)){
                                            unit = unitItemPoJo.getValue();
                                            if (Objects.nonNull(parentId) && Objects.nonNull(productUnitPriceEntityMap)){
                                                List<ProductUnitPriceEntity> productUnitPriceEntityList = productUnitPriceEntityMap.getOrDefault(parentId, new ArrayList<>());
                                                Map<Long, ProductUnitPriceEntity> unitPriceEntityMap = productUnitPriceEntityList.stream().collect(Collectors.toMap(ProductUnitPriceEntity::getProductId, ProductUnitPriceEntity->ProductUnitPriceEntity));
                                                ProductUnitPriceEntity productUnitPriceEntity = unitPriceEntityMap.getOrDefault(productId, new ProductUnitPriceEntity());
                                                Map<Long, Double> priceMap = productUnitPriceEntity.getPrice().toJavaList(MultiUnitPricePoJo.class).stream().collect(Collectors.toMap(MultiUnitPricePoJo::getValue, MultiUnitPricePoJo::getRate));
                                                if (hasAddPrice){
                                                    productJsonObject.put(ProductConstant.PRICE, productUnitPriceEntity.getPrice());
                                                }
                                                price = priceMap.get(unitItemPoJo.getValue());
                                            }
                                            businessUnitItemPoJo = unitItemPoJo;
                                            break;
                                        }
                                    }
                                    productJsonObject.put(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr(), BasicConstant.ONE);
                                    productJsonObject.put(ProductConstant.UNIT_RATE, groupMessage.getItemDataPoJoList());
                                    productJsonObject.put(ProductConstant.TRANSFORM_UNIT_RATE, groupMessage.getItemDataPoJoList());
                                    //期初仓库产品保存数据特殊处理
                                    if (Objects.equals(XbbRefTypeEnum.ORI_STOCK.getCode(), businessType)){
                                        productJsonObject.put(SelectProductEnum.BUSINESS_UNIT.getAttr(), unit);
                                        productJsonObject.put(SelectProductEnum.BUSINESS_NUM.getAttr(), businessUnitNum);
                                        productJsonObject.put(SelectProductEnum.RATE.getAttr(), businessUnitItemPoJo.getRate());
                                        productJsonObject.put(SelectProductEnum.UNIT_GROUP.getAttr(), unitGroupId);
                                    }
                                }else {
                                    unit = paasFormDataEntityExt.getData().getString(ProductEnum.UNIT.getAttr());
                                }
                                stock = paasFormDataEntityExt.getData().getDouble(ProductEnum.STOCK.getAttr());
                                sheflifeDays = paasFormDataEntityExt.getData().get(ProductEnum.SHELF_LIFE_DAYS.getAttr());
                                //导入  将是否开启批次号和序列号标识放入参数中  开启序列号的直接不允许导入
                                productJsonObject.put(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getSaasAttr(), paasFormDataEntityExt.getData().get(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getAttr()));
                                productJsonObject.put(ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr(), paasFormDataEntityExt.getData().get(ProductEnum.ENABLE_SERIAL_NUMBER.getAttr()));
                                if (Objects.isNull(sheflifeDays)){
                                    productJsonObject.put(ProductEnum.SHELF_LIFE_DAYS.getSaasAttr(), BasicConstant.ZERO);
                                }else {
                                    productJsonObject.put(ProductEnum.SHELF_LIFE_DAYS.getSaasAttr(), BasicConstant.ONE);
                                }
                                if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.OTHER_OUTSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode())
                                  || Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.PURCHASE_INSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.REFUND_INSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.OTHER_INSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode())
                                  || Objects.equals(businessType, XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.INVENTORY.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.TRANSFER.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.ASSEMBLE.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.RETURNED_PURCHASE.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.ORI_STOCK.getCode())){
                                    if (BasicConstant.ONE.equals(paasFormDataEntityExt.getData().getInteger(ProductEnum.ENABLE_SERIAL_NUMBER.getAttr()))){
                                        errorString.append(String.format(ImportErrorCodeEnum.API_ERROR_235043.getMsg(), paasFormDataEntityExt.getData().get(ProductEnum.NAME.getAttr()), parentTitle)).append("(").append(productNo).append(")");
                                    }
                                    //开启批次号  批次号必填校验
                                    if (BasicConstant.ONE.equals(paasFormDataEntityExt.getData().getInteger(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getAttr()))){
                                        if (Objects.equals(batchNo, "") || Objects.isNull(batchNo)){
                                            errorString.append(String.format(ImportErrorCodeEnum.API_ERROR_235044.getMsg(), paasFormDataEntityExt.getData().get(ProductEnum.NAME.getAttr()), parentTitle)).append("(").append(productNo).append(")");
                                        }
                                    }
                                }
                                break;
                            }
                        } else {
                            // 单规格可以不用填规格字段
                                productId = paasFormDataEntityExt.getId();
                                parentId = paasFormDataEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                                price = paasFormDataEntityExt.getData().getDouble(ProductEnum.PRICE.getAttr());
                                cost = paasFormDataEntityExt.getData().getDouble(ProductEnum.COST.getAttr());
                                //多单位产品 单位的value不能直接塞单位组的ID  bom 盘点 供应商的单位导入不填在下面塞
                                if (Objects.equals(BasicConstant.ONE,paasFormDataEntityExt.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr())) && !StockConstant.IMPORT_MULTI_UNIT_TYPE.contains(businessType)){
                                    Long unitGroupId = paasFormDataEntityExt.getData().getLong(ProductEnum.UNIT.getAttr());
                                    MultiUnitItemPoJo groupMessage = groupBaseUnitMap.getOrDefault(Objects.toString(unitGroupId,""), new MultiUnitItemPoJo());
                                    List<String> unitTextList = new ArrayList<>();
                                    UnitItemPoJo businessUnitItemPoJo = null;
                                    for (UnitItemPoJo unitItemPoJo : groupMessage.getItemDataPoJoList()) {
                                        unitTextList.add(unitItemPoJo.getText());
                                    }
                                    // 多单位产品  业务单据导入单位不填或者填写的不是单位组中的基本单位  默认给基本单位
                                    if (Objects.isNull(unitText) || StringUtil.isEmpty(unitText.toString()) || !unitTextList.contains(unitText)){
                                       unitText = groupMessage.getBaseName();
                                    }
                                    for (UnitItemPoJo unitItemPoJo : groupMessage.getItemDataPoJoList()) {
                                        if (Objects.equals(unitItemPoJo.getText(), unitText)){
                                            unit = unitItemPoJo.getValue();
                                            if (Objects.nonNull(parentId) && Objects.nonNull(productUnitPriceEntityMap)){
                                                List<ProductUnitPriceEntity> productUnitPriceEntityList = productUnitPriceEntityMap.getOrDefault(parentId, new ArrayList<>());
                                                Map<Long, ProductUnitPriceEntity> unitPriceEntityMap = productUnitPriceEntityList.stream().collect(Collectors.toMap(ProductUnitPriceEntity::getProductId, ProductUnitPriceEntity->ProductUnitPriceEntity));
                                                ProductUnitPriceEntity productUnitPriceEntity = unitPriceEntityMap.getOrDefault(productId, new ProductUnitPriceEntity());
                                                Map<Long, Double> priceMap = productUnitPriceEntity.getPrice().toJavaList(MultiUnitPricePoJo.class).stream().collect(Collectors.toMap(MultiUnitPricePoJo::getValue, MultiUnitPricePoJo::getRate));
                                                if (hasAddPrice){
                                                    productJsonObject.put(ProductConstant.PRICE, productUnitPriceEntity.getPrice());
                                                }
                                                price = priceMap.get(unitItemPoJo.getValue());
                                            }
                                            businessUnitItemPoJo = unitItemPoJo;
                                            break;
                                        }
                                    }
                                    productJsonObject.put(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr(), BasicConstant.ONE);
                                    productJsonObject.put(ProductConstant.UNIT_RATE, groupMessage.getItemDataPoJoList());
                                    productJsonObject.put(ProductConstant.TRANSFORM_UNIT_RATE, groupMessage.getItemDataPoJoList());
                                    //期初仓库产品保存数据特殊处理
                                    if (Objects.equals(XbbRefTypeEnum.ORI_STOCK.getCode(), businessType)){
                                        productJsonObject.put(SelectProductEnum.BUSINESS_UNIT.getAttr(), unit);
                                        productJsonObject.put(SelectProductEnum.BUSINESS_NUM.getAttr(), businessUnitNum);
                                        productJsonObject.put(SelectProductEnum.RATE.getAttr(), businessUnitItemPoJo.getRate());
                                        productJsonObject.put(SelectProductEnum.UNIT_GROUP.getAttr(), unitGroupId);
                                    }
                                }else {
                                    unit = paasFormDataEntityExt.getData().getString(ProductEnum.UNIT.getAttr());
                                }

                                stock = paasFormDataEntityExt.getData().getDouble(ProductEnum.STOCK.getAttr());
                                sheflifeDays = paasFormDataEntityExt.getData().get(ProductEnum.SHELF_LIFE_DAYS.getAttr());
                                //导入  将是否开启批次号和序列号标识放入参数中  开启序列号的直接不允许导入
                                productJsonObject.put(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getSaasAttr(), paasFormDataEntityExt.getData().get(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getAttr()));
                                productJsonObject.put(ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr(), paasFormDataEntityExt.getData().get(ProductEnum.ENABLE_SERIAL_NUMBER.getAttr()));
                                if (Objects.isNull(sheflifeDays)){
                                    productJsonObject.put(ProductEnum.SHELF_LIFE_DAYS.getSaasAttr(), BasicConstant.ZERO);
                                }else {
                                    productJsonObject.put(ProductEnum.SHELF_LIFE_DAYS.getSaasAttr(), BasicConstant.ONE);
                                }
                                if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.OTHER_OUTSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode())
                                      || Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.PURCHASE_INSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.REFUND_INSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.OTHER_INSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode())
                                      || Objects.equals(businessType, XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.INVENTORY.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.TRANSFER.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.ASSEMBLE.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.RETURNED_PURCHASE.getCode())
                                      || Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.ORI_STOCK.getCode())){
                                      if (BasicConstant.IS_DEFAULT.equals(paasFormDataEntityExt.getData().get(ProductEnum.ENABLE_SERIAL_NUMBER.getAttr()))){
                                            errorString.append(String.format(ImportErrorCodeEnum.API_ERROR_235043.getMsg(), paasFormDataEntityExt.getData().get(ProductEnum.NAME.getAttr()), parentTitle)).append("(").append(productNo).append(")");
                                      }
                                      //开启批次号  批次号必填校验
                                      if (BasicConstant.IS_DEFAULT.equals(paasFormDataEntityExt.getData().get(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getAttr()))){
                                          if (Objects.equals(batchNo, "") || Objects.isNull(batchNo)){
                                              errorString.append(String.format(ImportErrorCodeEnum.API_ERROR_235044.getMsg(), paasFormDataEntityExt.getData().get(ProductEnum.NAME.getAttr()), parentTitle)).append("(").append(productNo).append(")");
                                          }
                                      }
                                }
                        }
                    }
                    if (Objects.isNull(productId)) {
                        errorString.append(ProductErrorCodeEnum.API_ERROR_205040.getMsg()).append("(").append(productNo).append(")");
                        break Outter;
                    }
                    JSONObject idObject = new JSONObject();
                    idObject.put(StringConstant.DATA_ID, productId);
                    productJsonObject.put(SelectProductEnum.PRODUCT.getAttr(), idObject);
                    if (hasPriceList.contains(businessType)) {
                        productJsonObject.put(SelectProductEnum.PRICE.getAttr(), price);
                    }
                    if (hasStockList.contains(businessType)) {
                        productJsonObject.put(SelectProductEnum.STOCK.getAttr(), stock);
                    }
                    if (Objects.equals(XbbRefTypeEnum.PRODUCTION_ORDER.getCode(), businessType) && Objects.equals(fieldAttrEntityForImport.getAttr(), ProductionOrderEnum.MATERIEL.getAttr())) {
                        productJsonObject.put(SelectProductEnum.LOSS_RATE.getAttr(), 0D);
                    }
                    if (Objects.isNull(productJsonObject.get(SelectProductEnum.COST.getAttr())) && Objects.nonNull(cost)
                            && !Objects.equals(businessType, XbbRefTypeEnum.ORI_STOCK.getCode())) {
                        productJsonObject.put(SelectProductEnum.COST.getAttr(), cost);
                    }
                    if (hasParentId) {
                        productJsonObject.put(ProductEnum.PARENT_ID.getSaasAttr(), parentId);
                    }
                    JSONObject unitObject = new JSONObject();
                    unitObject.put(StringConstant.VALUE, unit);
                    // 其他的单位回显
                    unitObject.put(FieldTypeEnum.TEXT.getAlias(), unitText);
                    productJsonObject.put(SelectProductEnum.UNIT.getAttr(), unitObject);
                } else if (Objects.equals(subAttr, SelectProductEnum.NUM.getAttr()) && isSystemField) {
                    if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                        errorString.append(ProductErrorCodeEnum.API_ERROR_205039.getMsg()).append("(").append(productNo).append(")");
                        break Outter;
                    } else if (!RegexUtil.isNumber(subFormCellValue.toString())) {
                        errorString.append(String.format(ImportErrorCodeEnum.API_ERROR_235006.getMsg(), subAttrName)).append("(").append(productNo).append(")");
                        break Outter;
                    }
                    productJsonObject.put(subAttr, StringUtil.toDouble(subFormCellValue.toString()));
                    if (hasSellPriceTotalList.contains(businessType) && Objects.nonNull(productJsonObject.get(SelectProductEnum.SELLING_PRICE.getAttr())) && Objects.nonNull(productJsonObject.get(SelectProductEnum.NUM.getAttr()))) {
                        Double sellPriceTotal = Arith.mul(productJsonObject.getDouble(SelectProductEnum.SELLING_PRICE.getAttr()), productJsonObject.getDouble(SelectProductEnum.NUM.getAttr()));
                        productJsonObject.put(SelectProductEnum.SUBTOTAL.getAttr(), sellPriceTotal);
                    }
                    if (hasPriceTotalList.contains(businessType) && Objects.nonNull(productJsonObject.get(SelectProductEnum.PRICE.getAttr())) && Objects.nonNull(productJsonObject.get(SelectProductEnum.NUM.getAttr()))) {
                        Double priceTotal = Arith.mul(productJsonObject.getDouble(SelectProductEnum.PRICE.getAttr()), productJsonObject.getDouble(SelectProductEnum.NUM.getAttr()));
                        productJsonObject.put(SelectProductEnum.SUBTOTAL.getAttr(), priceTotal);
                    }
                    if (hasCostTotalList.contains(businessType) && Objects.nonNull(productJsonObject.getDouble(SelectProductEnum.COST.getAttr())) && Objects.nonNull(productJsonObject.getDouble(SelectProductEnum.NUM.getAttr()))) {
                        Double costTotal = Arith.mul(productJsonObject.getDouble(SelectProductEnum.COST.getAttr()), productJsonObject.getDouble(SelectProductEnum.NUM.getAttr()));
                        productJsonObject.put(SelectProductEnum.TOTAL_COST.getAttr(), costTotal);
                    }
                } else if (Objects.equals(subAttr, SelectProductEnum.WAREHOUSE.getAttr()) && isSystemField) {
                    if ((Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString()))
                            && Objects.equals(subFormFieldAttr.getRequired(), 1)) {
                        errorString.append(String.format(WarehouseErrorCodeEnum.API_ERROR_244016.getMsg(), subAttrName)).append("(").append(productNo).append(")");
                        break Outter;
                    }
                    List<ItemPoJo> itemPoJoList = subFormFieldAttr.getItems();
                    for (ItemPoJo itemPoJo : itemPoJoList) {
                        if (Objects.equals(subFormCellValue.toString(), itemPoJo.getText())) {
                            JSONArray jsonArray = new JSONArray();
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, itemPoJo.getValue());
                            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, itemPoJo.getText());
                            jsonObject.put(StringConstant.DATA_ID, itemPoJo.getValue());
                            jsonArray.add(jsonObject);
                            productJsonObject.put(subAttr, jsonArray);
                            break;
                        }
                    }
                    if (Objects.isNull(productJsonObject.get(SelectProductEnum.WAREHOUSE.getAttr()))) {
                        errorString.append(String.format(ImportErrorCodeEnum.API_ERROR_235008.getMsg(), subAttrName)).append("(").append(productNo).append(")");
                        break Outter;
                    }
                } else if (Objects.equals(subAttr, SelectProductEnum.COST.getAttr()) && isSystemField) {
                    if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                        productJsonObject.put(subAttr, 0D);
                    } else if (!RegexUtil.isNumber(subFormCellValue.toString())) {
                        errorString.append(String.format(ImportErrorCodeEnum.API_ERROR_235006.getMsg(), subAttrName)).append("(").append(productNo).append(")");
                        break Outter;
                    } else {
                        productJsonObject.put(subAttr, subFormCellValue);
                    }
                    if (hasCostTotalList.contains(businessType) && Objects.nonNull(productJsonObject.get(SelectProductEnum.COST.getAttr())) && Objects.nonNull(productJsonObject.get(SelectProductEnum.NUM.getAttr()))) {
                        Double costTotal = Arith.mul(productJsonObject.getDouble(SelectProductEnum.COST.getAttr()), productJsonObject.getDouble(SelectProductEnum.NUM.getAttr()));
                        productJsonObject.put(SelectProductEnum.TOTAL_COST.getAttr(), costTotal);
                    }
                } else if (Objects.equals(subAttr, SelectProductEnum.DISCOUNT.getAttr()) && isSystemField) {
                    if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                        productJsonObject.put(subAttr, 100);
                    } else if (!RegexUtil.isNumber(subFormCellValue.toString())) {
                        errorString.append(String.format(ImportErrorCodeEnum.API_ERROR_235006.getMsg(), subAttrName)).append("(").append(productNo).append(")");
                        break Outter;
                    } else {
                        productJsonObject.put(subAttr, subFormCellValue);
                    }
                } else if ((Objects.equals(subAttr, SelectProductEnum.SELLING_PRICE.getAttr()) || Objects.equals(subAttr, SelectProductEnum.LOSS_RATE.getAttr())) && isSystemField) {
                    if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                        productJsonObject.put(subAttr, 0);
                    } else if (!RegexUtil.isNumber(subFormCellValue.toString())) {
                        errorString.append(String.format(ImportErrorCodeEnum.API_ERROR_235006.getMsg(), subAttrName)).append("(").append(productNo).append(")");
                        break Outter;
                    } else {
                        productJsonObject.put(subAttr, subFormCellValue);
                    }
                    if (hasSellPriceTotalList.contains(businessType) && Objects.nonNull(productJsonObject.get(SelectProductEnum.SELLING_PRICE.getAttr())) && Objects.nonNull(productJsonObject.get(SelectProductEnum.NUM.getAttr()))) {
                        Double sellPriceTotal = Arith.mul(productJsonObject.getDouble(SelectProductEnum.SELLING_PRICE.getAttr()), productJsonObject.getDouble(SelectProductEnum.NUM.getAttr()));
                        productJsonObject.put(SelectProductEnum.SUBTOTAL.getAttr(), sellPriceTotal);
                    }
                } else if ((Objects.equals(subAttr, SelectProductEnum.PRODUCE_DATE.getAttr()) || Objects.equals(subAttr, SelectProductEnum.GUARANTEE_PERIOD.getAttr())
                        || Objects.equals(subAttr, SelectProductEnum.MEMO.getAttr()) || Objects.equals(subAttr, SelectProductEnum.BATCH.getAttr())) && isSystemField) {
                    if (Objects.isNull(subFormCellValue) || StringUtil.isEmpty(subFormCellValue.toString())) {
                        continue;
                    }
                    if (Objects.equals(subFormFieldAttr.getAttr(), SelectProductEnum.PRODUCE_DATE.getAttr())) {
                        Long time = DateTimeUtil.getExcelTime(subFormCellValue.toString());
                        if (time == 0L) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.FORMAT_INVALID, subFormFieldAttr.getAttrName());
                        }
                        subFormCellValue = time;
                    } else if (Objects.equals(subFormFieldAttr.getAttr(), SelectProductEnum.GUARANTEE_PERIOD.getAttr())) {
                        if (!StringUtil.isDigital(subFormCellValue.toString())) {
                            errorString.append(String.format(ImportErrorCodeEnum.API_ERROR_235006.getMsg(), subAttrName)).append("(").append(productNo).append(")");
                            break Outter;
                        }
                    }
                    productJsonObject.put(subAttr, subFormCellValue);
                } else if (Objects.equals(subAttr, SelectProductEnum.PRODUCT_NAME.getAttr())) {
                } else if (commonHandleFieldType.contains(subFormFieldAttr.getFieldType())) {
                    if (Objects.nonNull(subFormCellValue) && StringUtil.isNotEmpty(subFormCellValue.toString())) {
                        formatCommonField(productJsonObject, subFormFieldAttr, subFormCellValue);
                    }
                } else if (Objects.equals(ProductEnum.UNIT.getAttr(), subAttr)){
                }else {
                    productJsonObject.put(subAttr, subFormCellValue);
                }
            }
            //BOM单和盘点单供应商导入时不需要填写单位 默认填充基本单位
            if (StockConstant.IMPORT_MULTI_UNIT_TYPE.contains(businessType)){
                if (Objects.isNull(temp)) {
                    throw new XbbException(ImportErrorCodeEnum.API_ERROR_235034);
                }
                for (PaasFormDataEntityExt paasFormDataEntityExt : temp) {
                    Object productUnit = paasFormDataEntityExt.getData().get(ProductEnum.UNIT.getAttr());
                    Boolean isMutilUnit = false;
                    if (Objects.nonNull(productUnit)){
                        isMutilUnit = StringUtil.isDigital(paasFormDataEntityExt.getData().get(ProductEnum.UNIT.getAttr()).toString()) && Long.valueOf(paasFormDataEntityExt.getData().get(ProductEnum.UNIT.getAttr()).toString()) > 1000;
                    }
                    if (isMutilUnit && Objects.equals(BasicConstant.ONE, paasFormDataEntityExt.getData().get(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))){
                        Long groupId = paasFormDataEntityExt.getData().getLong(ProductEnum.UNIT.getAttr());
                        if (groupBaseUnitMap == null) {
                            groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitStringMap(corpid);
                        }
                        if (groupBaseUnitMap != null && groupBaseUnitMap.containsKey(groupId.toString())) {
                            MultiUnitItemPoJo unitGroup = groupBaseUnitMap.get(groupId.toString());
                            JSONObject unitObject = new JSONObject();
                            unitObject.put(FieldTypeEnum.TEXT.getAlias(), unitGroup.getBaseName());
                            unitObject.put(StringConstant.VALUE, unitGroup.getBaseValue());
                            productJsonObject.put(ProductEnum.UNIT.getAttr(),unitObject);
                        }
                    }
                }
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        }
        return errorString.toString();
    }

    public void formatCommonField(JSONObject dataJson, FieldAttrEntityForImport fieldAttr, Object cellValue) throws XbbException {
        if (Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.USER.getType())  || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.DEPT.getType()) || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.DEPARTMENTID.getType()) || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.CREATORID.getType())) {
            formatUserOrDept4Import(dataJson, fieldAttr, cellValue);
        } else if (Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.USER_GROUP.getType()) || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.DEPT_GROUP.getType())
                || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.OWNERID.getType()) || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.COUSERID.getType()) || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.PURCHASEABLE_GOODS.getType())) {
            formatUserOrDeptGroup4Import(dataJson, fieldAttr, cellValue);
        } else if (Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.STAR.getType()) || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.COMBO.getType()) || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.RADIO_GROUP.getType())) {
            formatDropDownValue4Import(dataJson, fieldAttr, cellValue);
        } else if (Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.CHECKBOX_GROUP.getType()) || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.COMBO_CHECK.getType())) {
            formatDropDownList4Import(dataJson, fieldAttr, cellValue);
        } else if (Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.DATETIME.getType()) || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.ADDTIME.getType())
            || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.UPDATETIME.getType()) || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.ENDTIME.getType())
            || Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.CLOSETIME.getType())) {
            if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                return;
            }
            Long time = DateTimeUtil.getExcelTime(cellValue.toString());
            if (time == 0L) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.FORMAT_INVALID, fieldAttr.getAttrName());
            }
            dataJson.put(fieldAttr.getAttr(), time);
        } else if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), fieldAttr.getFieldType())) {
            if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                return;
            }
            formatStageValue4Import(dataJson, fieldAttr, cellValue);
        }
    }

    /**
     * 导出库存产品格式化
     * @param stockObj
     * @param stockInfoEntity
     */
    public void formatStockInfo4Export(JSONObject stockObj, ProductStockInfoEntity stockInfoEntity) {
        if (stockInfoEntity != null) {
            String batch = stockInfoEntity.getBatch();
            stockObj.put(StockProductEnum.BATCH.getAttr(), batch);
            Long produceDate = stockInfoEntity.getProduceDate();
            if (produceDate == null || produceDate == 0L) {
                stockObj.put(StockProductEnum.PRODUCE_DATE.getAttr(), "");
            } else {
                String produceDateStr = DateTimeUtil.getStringEpochSecond(produceDate, DateTimeUtil.SDFDate);
                stockObj.put(StockProductEnum.PRODUCE_DATE.getAttr(), produceDateStr);
            }
            if (stockInfoEntity.getGuaranteePeriod() == null) {
                stockObj.put(StockProductEnum.GUARANTEE_PERIOD.getAttr(), "");
            } else {
                Long guaranteePeriod = stockInfoEntity.getGuaranteePeriod();
                Double guaranteePeriodDay = guaranteePeriod / 86400D;
                stockObj.put(StockProductEnum.GUARANTEE_PERIOD.getAttr(), guaranteePeriodDay);
            }
            String memo = stockInfoEntity.getMemo();
            stockObj.put(StockProductEnum.MEMO.getAttr(), memo);
        }
    }

    /**
     * 阶段推进器数据格式处理
     * @param dataJson
     * @param fieldAttr
     * @param cellValue
     * @throws XbbException
     */
    private void formatStageValue4Import(JSONObject dataJson, FieldAttrEntityForImport fieldAttr, Object cellValue) throws XbbException {
        List<ItemPoJo> items = fieldAttr.getItems();
        if (CollectionsUtil.isNotEmpty(items)) {
            for (ItemPoJo item : items) {
                if (Objects.equals(item.getText(), cellValue)) {
                    dataJson.put(fieldAttr.getAttr(), item.getValue());
                    dataJson.put(PaasStageEnum.STAGE_PROCESS_ID.getAttr(), item.getStageProcessId());
                    dataJson.put(PaasStageEnum.STAGE_ID.getAttr(), item.getStageId());
                    dataJson.put(PaasStageEnum.STAGE_RATIO.getAttr(), item.getStageRatio());
                    break;
                }
            }
        }
        if (!dataJson.containsKey(fieldAttr.getAttr()) && Objects.equals(fieldAttr.getRequired(), 1)) {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235008, String.format(ImportErrorCodeEnum.API_ERROR_235008.getMsg(), fieldAttr.getAttrName()));
        }

    }

    /**
     * 导出库存产品格式化
     * @param stockObj
     */
    public void formatBatch4Export(JSONObject stockObj) {
        if (stockObj != null) {
            Long produceDate = stockObj.getLong(SelectProductEnum.PRODUCE_DATE.getAttr());
            if (produceDate == null || produceDate == 0L) {
                stockObj.put(SelectProductEnum.PRODUCE_DATE.getAttr(), "");
                stockObj.remove(SelectProductEnum.GUARANTEE_PERIOD.getAttr());
            } else {
                String produceDateStr = DateTimeUtil.getStringEpochSecond(produceDate, DateTimeUtil.SDFDate);
                stockObj.put(SelectProductEnum.PRODUCE_DATE.getAttr(), produceDateStr);
                stockObj.put(SelectProductEnum.GUARANTEE_PERIOD.getAttr(), stockObj.get(SelectProductEnum.GUARANTEE_PERIOD.getAttr()));
            }
        }
    }

    /**
     * 导出库存产品格式化
     * @param stockObj
     * @param baseInfoEntity
     */
    public void formatBaseInfo4Export(JSONObject stockObj, ProductBaseInfoEntity baseInfoEntity) {
        if (baseInfoEntity != null) {
            String batch = baseInfoEntity.getBatch();
            stockObj.put(SelectProductEnum.BATCH.getAttr(), batch);
            Long produceDate = baseInfoEntity.getProduceDate();
            if (produceDate == null || produceDate == 0L) {
                stockObj.put(SelectProductEnum.PRODUCE_DATE.getAttr(), "");
            } else {
                String produceDateStr = DateTimeUtil.getStringEpochSecond(produceDate, DateTimeUtil.SDFDate);
                stockObj.put(SelectProductEnum.PRODUCE_DATE.getAttr(), produceDateStr);
            }
            if (Objects.isNull(stockObj.get(SelectProductEnum.GUARANTEE_PERIOD.getAttr()))) {
                if (baseInfoEntity.getGuaranteePeriod() == null) {
                    stockObj.put(SelectProductEnum.GUARANTEE_PERIOD.getAttr(), "");
                } else {
                    Long guaranteePeriod = baseInfoEntity.getGuaranteePeriod();
                    Long guaranteePeriodDay = guaranteePeriod / 86400;
                    if (!Objects.equals(guaranteePeriodDay, 0L)) {
                        stockObj.put(SelectProductEnum.GUARANTEE_PERIOD.getAttr(), guaranteePeriodDay);
                    }
                }
            }
            String memo = baseInfoEntity.getMemo();
            stockObj.put(SelectProductEnum.MEMO.getAttr(), memo);
        } else {
            stockObj.entrySet().removeIf(entry ->(Objects.equals(entry.getKey(), SelectProductEnum.PRODUCE_DATE.getAttr()) && Objects.equals(entry.getValue(), 0))
                    || Objects.equals(entry.getKey(), SelectProductEnum.GUARANTEE_PERIOD.getAttr()) && Objects.equals(entry.getValue(), 0));
        }
    }

    /**
     * 格式化关联产品导出
     *
     * @param productMap
     * @param warehouseMap
     * @param productId
     * @param num
     * @param warehouseId
     * @param productObj
     */
    public void formatProduct4Export(Map<Long, ProductEntityExt> productMap, Map<Long, WarehouseEntityExt> warehouseMap, Long productId, Double num, Long warehouseId, JSONObject productObj) {
        if (productMap.containsKey(productId)) {
            ProductEntityExt productEntity = productMap.get(productId);
            JSONObject productJson = productEntity.getData();
            String name = productJson.getString(ProductEnum.NAME.getAttr());
            productObj.put(SelectProductEnum.PRODUCT_NAME.getAttr(), name);
            String productNo = productJson.getString(ProductEnum.PRODUCT_NO.getAttr());
            Long parentId = productJson.getLong(ProductEnum.PARENT_ID.getAttr());
            if (parentId != null && parentId != 0L && productMap.containsKey(parentId)) {
                ProductEntityExt parentProduct = productMap.get(parentId);
                productNo = parentProduct.getSerialNo();
            }
            productObj.put(SelectProductEnum.PRODUCT_NO.getAttr(), productNo);
            String spec = productJson.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
            productObj.put(SelectProductEnum.SPECIFICATION.getAttr(), spec);
            if (StringUtil.isNotEmpty(spec) && Objects.equals(spec, "{}")) {
                productObj.put(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
            }
            //到期日期格式转换
            Long expireDate = productObj.getLong(SelectProductEnum.EXPIRE_DATE.getAttr());
            if (Objects.nonNull(expireDate)){
                if (expireDate == 0L) {
                    productObj.put(SelectProductEnum.EXPIRE_DATE.getAttr(), "");
                } else {
                    String expireDateStr = DateTimeUtil.getStringEpochSecond(expireDate, DateTimeUtil.SDFDate);
                    productObj.put(SelectProductEnum.EXPIRE_DATE.getAttr(), expireDateStr);
                }
            }
            productObj.put(SelectProductEnum.BARCODE.getAttr(), productJson.getString(ProductEnum.BARCODE.getAttr()));
            productObj.put(SelectProductEnum.UNIT.getAttr(), productJson.get(ProductEnum.UNIT.getAttr()));
            productObj.put(ProductEnum.ENABLE_MULTI_UNIT.getAttr(), productJson.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
        }
        productObj.put(SelectProductEnum.NUM.getAttr(), num);
        if (warehouseMap != null && warehouseId != null && warehouseMap.containsKey(warehouseId)) {
            String warehouseName = warehouseMap.get(warehouseId).getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr());
            productObj.put(SelectProductEnum.WAREHOUSE.getAttr(), warehouseName);
        }
    }

    /**
     * 导出数据通用转换
     * @param userMap
     * @param paasFormDataEntityExt
     * @param formDataObj
     * @param explainList
     * @param phoneMap
     */
    public void formatCommonData4Export(Map<String, Object> userMap, Map<String, Object> deptMap, PaasFormDataEntityExt paasFormDataEntityExt,
                                        JSONObject formDataObj, List<? extends FieldAttrEntity> explainList, Map<Long, String> phoneMap,
                                        ExportLinkDataPojo exportLinkDataPojo, Integer businessType, Map<String, Object> purchaseableGoodsMap) {
        String corpid = paasFormDataEntityExt.getCorpid();
        boolean notHaveOwnerId = !formDataObj.containsKey(FieldTypeEnum.OWNERID.getAlias()) &&  CollectionsUtil.isNotEmpty(formDataObj.getJSONArray(FieldTypeEnum.OWNERID.getAlias()));
        if (notHaveOwnerId) {
            formDataObj.put(FieldTypeEnum.OWNERID.getAlias(), "");
        }
        boolean notHaveCoUserId = !formDataObj.containsKey(FieldTypeEnum.COUSERID.getAlias()) &&  CollectionsUtil.isNotEmpty(formDataObj.getJSONArray(FieldTypeEnum.COUSERID.getAlias()));
        if (notHaveCoUserId) {
            formDataObj.put(FieldTypeEnum.COUSERID.getAlias(), "");
        }
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            String attr = fieldAttrEntity.getAttr();
            Integer fieldType = fieldAttrEntity.getFieldType();
            if (Objects.equals(fieldAttrEntity.getSaasAttr(), StringConstant.LAST_CONNECT_TIME_SAAS_ATTR) && Objects.equals(fieldType, FieldTypeEnum.DATETIME.getType())) {
                Long timeEpochSecond = formDataObj.getLong(attr);
                formDataObj.put(attr, DateTimeUtil.getLastConnectTimeStr(timeEpochSecond));

                FormConfigGetDTO formConfigGetDTO = new FormConfigGetDTO();
                formConfigGetDTO.setCorpid(paasFormDataEntityExt.getCorpid());
                formConfigGetDTO.setBusinessType(businessType);
                formConfigGetDTO.setFormId(paasFormDataEntityExt.getFormId());
                Map<String, String> lastConnectTimeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                try {
                    lastConnectTimeMap = formDataListAnalysisDataHelp.lastConnectTime(formConfigGetDTO);
                } catch (XbbException e) {
                    e.printStackTrace();
                }
                String lastConnectTime = "1";
                if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode())){
                    lastConnectTime = lastConnectTimeMap.get(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getConfig());
                }
                if(Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())){
                    lastConnectTime = lastConnectTimeMap.get(FormConfigEnum.SALES_OPPORTUNITY_LAST_CONNECT_TIME.getConfig());
                }
                if(Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
                    lastConnectTime = lastConnectTimeMap.get(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getConfig());
                }
                if(Objects.equals(lastConnectTime, "0")){
                    // 13位时间戳转换
                    if (Objects.nonNull(timeEpochSecond) && timeEpochSecond.toString().length() == 13){
                        timeEpochSecond = timeEpochSecond/1000;
                    }
                    String formatDateTime = DateTimeUtil.getStringEpochSecond(timeEpochSecond, DateTimeUtil.SDFYMDHM);
                    formDataObj.put(attr, formatDateTime);
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_SINGLE.getType())) {
                setLinkBusinessSingleData(formDataObj, fieldAttrEntity, phoneMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_MULTI.getType())) {
                setLinkBusinessMultiData(formDataObj, fieldAttrEntity);
            } else if (Objects.equals(fieldType, FieldTypeEnum.DATETIME.getType()) || Objects.equals(fieldType, FieldTypeEnum.UPDATETIME.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.ENDTIME.getType()) || Objects.equals(fieldType, FieldTypeEnum.ADDTIME.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.CLOSETIME.getType())) {
                String fieldDateType = fieldAttrEntity.getDateType();
                setDateTimeData(paasFormDataEntityExt, formDataObj, attr, fieldDateType, fieldType);
            } else if (Objects.equals(fieldType, FieldTypeEnum.BIRTHDAY.getType())) {
                String birthdayFlagAttr = fieldAttrEntity.getLinkedText();
                setBirthdayData(formDataObj, attr, birthdayFlagAttr);
            } else if (Objects.equals(fieldType, FieldTypeEnum.ADDRESS.getType())) {
                setAddressData(formDataObj, attr);
            } else if (Objects.equals(fieldType, FieldTypeEnum.LOCATION.getType())) {
                setLocationData(formDataObj, attr);
            } else if (Objects.equals(fieldType, FieldTypeEnum.HREF.getType())) {
                setHrefData(formDataObj, attr);
            } else if (Objects.equals(fieldType, FieldTypeEnum.SINGLE_SUB_FORM.getType()) || Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
                setSubFormData(formDataObj, attr, fieldAttrEntity, userMap, deptMap, paasFormDataEntityExt, exportLinkDataPojo, businessType);
            } else if (Objects.equals(fieldType, FieldTypeEnum.SERIALNO.getType())) {
                if (!Objects.equals(businessType, XbbRefTypeEnum.STOCK_FLOW_BILL.getCode()) && !Objects.equals(businessType, XbbRefTypeEnum.STOCK_STANDING_BOOK.getCode())) {
                    formDataObj.put(attr, paasFormDataEntityExt.getSerialNo());
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.OWNERID.getType()) || Objects.equals(fieldType, FieldTypeEnum.COUSERID.getType())) {
                try {
                    List<String> userIds = (List<String>)formDataObj.get(attr);
                    if (userIds.isEmpty()) {
                        formDataObj.put(attr, "");
                        continue;
                    }
                    StringBuilder value = new StringBuilder("");
                    for (String userId : userIds) {
                        if (userMap.containsKey(userId)) {
                            value.append(userMap.get(userId)).append(StringConstant.COMMA);
                        }
                    }
                    String valueString = value.toString();
                    if (StringUtil.isNotEmpty(valueString)) {
                        valueString = valueString.substring(0, valueString.length() - 1);
                    }
                    formDataObj.put(attr, valueString);
                } catch (Exception e) {
                    formDataObj.put(attr, "");
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.CREATORID.getType())) {
                formDataObj.put(attr, paasFormDataEntityExt.getCreatorId());
                setUserOrDeptData(formDataObj, attr, userMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.USER_GROUP.getType())) {
                setUserOrDeptGroupData(formDataObj, attr, userMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.USER.getType())) {
                if (Objects.equals(attr, ContractEnum.SIGN_PERSON.getAttr()) && Objects.equals(fieldAttrEntity.getSaasAttr(), ContractEnum.SIGN_PERSON.getSaasAttr())) {
                    String signId = formDataObj.getString(attr);
                    if (Objects.equals(signId, "-1") || Objects.equals(signId, "0")) {
                        String signName = formDataObj.getString(ContractEnum.SIGN_NAME.getAttr());
                        // 兼容一下离职人员名称显示
                        if(Objects.equals(signId, StringConstant.NOT_IN_SYSTEM_ID)){
                            signName =signName + StringConstant.LEAVE_ANOTHER_MARK;
                        }
                        if (StringUtil.isNotEmpty(signName)) {
                            formDataObj.put(attr, signName);
                        } else {
                            formDataObj.put(attr, "");
                        }
                    } else {
                        setUserOrDeptData(formDataObj, attr, userMap);
                    }
                } else {
                    setUserOrDeptData(formDataObj, attr, userMap);
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.DEPT.getType())) {
                setUserOrDeptData(formDataObj, attr, deptMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.DEPT_GROUP.getType())) {
                setUserOrDeptGroupData(formDataObj, attr, deptMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.PURCHASEABLE_GOODS.getType()) && Objects.nonNull(purchaseableGoodsMap)) {
                // 和DEPT_GROUP逻辑一样，先借用
                setUserOrDeptGroupData(formDataObj, attr, purchaseableGoodsMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.DEPARTMENTID.getType())) {
                formDataObj.put(attr, paasFormDataEntityExt.getDepartmentId());
                setUserOrDeptData(formDataObj, attr, deptMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.COMBO_LINK_BUSINESS.getType())) {
                setComboLinkBusiness(formDataObj, attr);
            } else if (Objects.equals(fieldType, FieldTypeEnum.SWITCH.getType())) {
                setSwitchData(formDataObj, attr);
            } else if (Objects.equals(fieldType, FieldTypeEnum.NUM.getType())) {
                if (Objects.nonNull(formDataObj.get(attr)) && formDataObj.get(attr) instanceof Double){
                    formDataObj.put(attr, attrDecimalPrecisionHelper.setDecPrecision(formDataObj.getDouble(attr), fieldAttrEntity.getAccuracy()));
                }
            } else if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldType)) {
                setLinkData(formDataObj, attr, exportLinkDataPojo, fieldAttrEntity.getLinkInfo(), corpid);
            } else if (Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), fieldType)) {
                setLinkDataMulti(formDataObj, attr, exportLinkDataPojo, fieldAttrEntity.getLinkInfo(), corpid);
            } else if (Objects.equals(FieldTypeEnum.ACCOUNT_PERIOD.getType(), fieldType)) {
                String receivavlePeriod = formDataObj.getString(attr);
                //格式话应收账期
                if (StringUtils.isNotEmpty(receivavlePeriod)) {
                    String receivavlePeriodText = fundSetHelp.getFormatReceivablePeriod(receivavlePeriod);
                    formDataObj.put(attr, receivavlePeriodText);
                }
            } else if (Objects.equals(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode(), businessType) && Objects.equals(CustomerCommunicateEnum.MEMO.getAttr(), fieldAttrEntity.getAttr())) {
                // 跟进记录-跟进内容，去除转义字符，后续重构需要改成策略模式
                String formattedValue = formDataObj.getString(attr);
                formattedValue = formattedValue == null ? "" : formattedValue;
                formattedValue = formattedValue.replaceAll("&amp;|nbsp;|&nbsp;|<span class=\"at-person\">|</span>", "");
                formDataObj.put(attr, formattedValue);
            }
        }
    }

    /**
     * 业务单据导出 关联产品解释拼接基本单位，基本单位数量
     * @param items 关联产品解释list
     * @param productItems
     */
    public void exportAddExplain(List<FieldAttrEntity> items, List<ItemPoJo> productItems) {
        List<FieldAttrEntity> explains = new ArrayList<>();
        Integer flag = -1;
        for (int i = 0; i < items.size(); i++) {
            if (Objects.equals(SelectProductEnum.NUM.getAttr(), items.get(i).getAttr())) {
                FieldAttrEntity fieldAttrEntitys = new FieldAttrEntity();
                fieldAttrEntitys.setAttr(SelectProductEnum.BASIC_UNIT_NUM.getAttr());
                fieldAttrEntitys.setAttrName(SelectProductEnum.BASIC_UNIT_NUM.getAttrName());
                fieldAttrEntitys.setSaasAttr(SelectProductEnum.BASIC_UNIT_NUM.getSaasAttr());
                fieldAttrEntitys.setDefaultName(SelectProductEnum.BASIC_UNIT_NUM.getAttrName());
                fieldAttrEntitys.setParentAttr(items.get(i).getParentAttr());
                fieldAttrEntitys.setAttrType(items.get(i).getAttrType());
                fieldAttrEntitys.setFieldType(items.get(i).getFieldType());
                fieldAttrEntitys.setVisible(items.get(i).getVisible());
                fieldAttrEntitys.setVisibleScopeEnable(items.get(i).getVisibleScopeEnable());
                fieldAttrEntitys.setAccuracy(items.get(i).getAccuracy());
                fieldAttrEntitys.setComboType(items.get(i).getComboType());
                fieldAttrEntitys.setIsRedundant(items.get(i).getIsRedundant());
                fieldAttrEntitys.setAmountFlag(items.get(i).getAmountFlag());
                fieldAttrEntitys.setSetType(items.get(i).getSetType());
                fieldAttrEntitys.setShowType(items.get(i).getShowType());
                fieldAttrEntitys.setIntegerOnly(items.get(i).getIntegerOnly());
                explains.add(fieldAttrEntitys);
                flag = i;
            } else if (Objects.equals(SelectProductEnum.UNIT.getAttr(), items.get(i).getAttr())) {
                FieldAttrEntity fieldAttrEntitys = new FieldAttrEntity();
                fieldAttrEntitys.setAttr(SelectProductEnum.BASIC_UNIT.getAttr());
                fieldAttrEntitys.setAttrName(SelectProductEnum.BASIC_UNIT.getAttrName());
                fieldAttrEntitys.setSaasAttr(SelectProductEnum.BASIC_UNIT.getSaasAttr());
                fieldAttrEntitys.setDefaultName(SelectProductEnum.BASIC_UNIT.getAttrName());
                fieldAttrEntitys.setParentAttr(items.get(i).getParentAttr());
                fieldAttrEntitys.setAttrType(items.get(i).getAttrType());
                fieldAttrEntitys.setFieldType(items.get(i).getFieldType());
                fieldAttrEntitys.setVisible(items.get(i).getVisible());
                fieldAttrEntitys.setVisibleScopeEnable(items.get(i).getVisibleScopeEnable());
                fieldAttrEntitys.setAccuracy(items.get(i).getAccuracy());
                fieldAttrEntitys.setVisibleScopeRule(items.get(i).getVisibleScopeRule());
                fieldAttrEntitys.setEditableRule(items.get(i).getEditableRule());
                fieldAttrEntitys.setAddRule(items.get(i).getAddRule());
                fieldAttrEntitys.setNumericalLimitsFlag(items.get(i).getNumericalLimitsFlag());
                fieldAttrEntitys.setNumericalLimits(items.get(i).getNumericalLimits());
                fieldAttrEntitys.setIsRedundant(items.get(i).getIsRedundant());
                fieldAttrEntitys.setIsForbidden(items.get(i).getIsForbidden());
                fieldAttrEntitys.setItems(productItems);
                items.get(i).setItems(productItems);
                explains.add(fieldAttrEntitys);
            }
        }
        //基本单位要在基本数量前面
        int baseUnitIndex = 0;
        int baseUnitaNumIndex = 0;
        for (int i = 0; i < explains.size(); i++) {
            if(Objects.equals(SelectProductEnum.BASIC_UNIT.getAttr() ,explains.get(i).getAttr())){
                baseUnitIndex = i;
            }else if(Objects.equals(SelectProductEnum.BASIC_UNIT_NUM.getAttr(), explains.get(i).getAttr())) {
                baseUnitaNumIndex = i;

            }
        }
        items.add(flag + BasicConstant.ONE,explains.get(baseUnitIndex));
        items.add(flag + 2,explains.get(baseUnitaNumIndex));
    }
    /**
     * 产品子表单内自定义字段导出解析
     * @param userMap
     * @param deptMap
     * @param formDataObj
     * @param fieldAttrEntity
     */
    public void formatRelativeProductData4Export(Map<String, Object> userMap, Map<String, Object> deptMap, JSONObject formDataObj, FieldAttrEntity fieldAttrEntity, ExportLinkDataPojo exportLinkDataPojo, String corpid) {
        String attr = fieldAttrEntity.getAttr();
        Integer fieldType = fieldAttrEntity.getFieldType();
        if (Objects.equals(fieldType, FieldTypeEnum.DATETIME.getType())) {
            String fieldDateType = fieldAttrEntity.getDateType();
            setDateTimeData(null, formDataObj, attr, fieldDateType, fieldType);
        } else if (Objects.equals(fieldType, FieldTypeEnum.ADDRESS.getType())) {
            setAddressData(formDataObj, attr);
        } else if (Objects.equals(fieldType, FieldTypeEnum.LOCATION.getType())) {
            setLocationData(formDataObj, attr);
        } else if (Objects.equals(fieldType, FieldTypeEnum.HREF.getType())) {
            setHrefData(formDataObj, attr);
        } else if (Objects.equals(fieldType, FieldTypeEnum.USER_GROUP.getType())) {
            setUserOrDeptGroupData(formDataObj, attr, userMap);
        } else if (Objects.equals(fieldType, FieldTypeEnum.USER.getType())) {
            setUserOrDeptData(formDataObj, attr, userMap);
        } else if (Objects.equals(fieldType, FieldTypeEnum.DEPT.getType())) {
            setUserOrDeptData(formDataObj, attr, deptMap);
        } else if (Objects.equals(fieldType, FieldTypeEnum.DEPT_GROUP.getType())) {
            setUserOrDeptGroupData(formDataObj, attr, deptMap);
        } else if (Objects.equals(fieldType, FieldTypeEnum.NUM.getType())) {
            if (Objects.nonNull(formDataObj.getDouble(attr))){
                formDataObj.put(attr, attrDecimalPrecisionHelper.setDecPrecision(formDataObj.getDouble(attr), fieldAttrEntity.getAccuracy()));
            }
        } else if (Objects.equals(fieldType, FieldTypeEnum.COMBO.getType()) || Objects.equals(fieldType, FieldTypeEnum.RADIO_GROUP.getType())) {
            setDropDownListData(formDataObj, attr, fieldAttrEntity);
        } else if (Objects.equals(fieldType, FieldTypeEnum.CHECKBOX_GROUP.getType()) || Objects.equals(fieldType, FieldTypeEnum.COMBO_CHECK.getType())) {
            setDropDownGroupData(formDataObj, attr, fieldAttrEntity);
        } else if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldType)) {
            setLinkData(formDataObj, attr, exportLinkDataPojo, fieldAttrEntity.getLinkInfo(), corpid);
        }
    }

    /**
     * 导出关联数据
     * @author 吴峰
     * @param formDataObj
     * @param attr
     */
    private void setLinkData(JSONObject formDataObj, String attr, ExportLinkDataPojo exportLinkDataPojo, LinkInfoPojo linkInfoPojo, String corpid) {
        if (Objects.isNull(exportLinkDataPojo)) {
            if (formDataObj.get(attr) instanceof List) {
                // 工单的关联数据格式
                setLinkData(formDataObj, attr);
            } else {
                formDataObj.put(attr, "");
            }
            return;
        }
        if (Objects.isNull(formDataObj.get(attr)) || !(formDataObj.get(attr) instanceof Number) || Objects.equals(0, formDataObj.getInteger(attr))) {
            formDataObj.put(attr, "");
            return;
        }
        Map<String, PaasFormExplainEntity> formExplainMap = exportLinkDataPojo.getFormExplainMap();
        Map<String, WorkOrderExplainEntity> workOrderExplainMap = exportLinkDataPojo.getWorkOrderFormExplainMap();
        Map<String, PaasFormDataEntityExt> formDataMap = exportLinkDataPojo.getFormDataMap();
        if(linkInfoPojo == null || linkInfoPojo.getLinkKey() == null){
            formDataObj.put(attr, "");
            return;
        }
        String linkKey = linkInfoPojo.getLinkKey();
        Long formId = linkInfoPojo.getLinkFormId();
        if(formId == null){
            formDataObj.put(attr, "");
            return;
        }
        PaasFormExplainEntity linkForm = new PaasFormExplainEntity();
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), linkInfoPojo.getLinkBusinessType())) {
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainMap.get(formId.toString());
            if (Objects.isNull(workOrderExplainEntity)) {
                formDataObj.put(attr, "");
                return;
            }
            BeanUtil.copyProperties(workOrderExplainEntity, linkForm);
        } else {
            linkForm = formExplainMap.get(formId.toString());
        }
        if(linkForm == null){
            formDataObj.put(attr, "");
            return;
        }
        Map<String, FieldAttrEntity> linkExplainMap = ExplainUtil.getExplainMap(linkForm.getExplains(), linkKey);
        FieldAttrEntity linkAttr = linkExplainMap.get(linkKey);
        if(linkAttr == null){
            formDataObj.put(attr, "");
            return;
        }
        String key = formDataObj.getString(attr);
        Integer saasMark = linkInfoPojo.getLinkSaasMark();
        if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
            key = linkInfoPojo.getLinkBusinessType() + "_" +key;
        }
        PaasFormDataEntityExt paasFormDataEntityExt = formDataMap.get(key);
        if(paasFormDataEntityExt == null){
            formDataObj.put(attr, "");
            return;
        }
        JSONObject targetData = paasFormDataEntityExt.getData();
        if(targetData == null){
            formDataObj.put(attr, "");
            return;
        }
        if (Objects.equals(linkInfoPojo.getLinkBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(linkInfoPojo.getLinkKey(), ProductEnum.UNIT.getAttr())){
            try {
                List<ItemPoJo> productItems = saasFormHelp.getProductItems(corpid);
                linkAttr.setItems(productItems);
            } catch (XbbException e) {
                e.printStackTrace();
            }
        }
        Object value = "";
        if (Objects.equals(FieldTypeEnum.COMBO.getType(), linkAttr.getFieldType()) || Objects.equals(FieldTypeEnum.RADIO_GROUP.getType(), linkAttr.getFieldType())) {
           value = ItemUtil.analysisComboReturnStr(targetData, linkAttr);
        } else if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), linkAttr.getFieldType())) {
            try {
                linkAttr.setItems(proFormHelp.getEditStageComboItems(linkAttr, linkInfoPojo.getLinkSaasMark(), linkInfoPojo.getLinkBusinessType(), corpid, linkInfoPojo.getLinkFormId(), targetData));
                value = ItemUtil.analysisComboReturnStr(targetData, linkAttr);
            } catch (XbbException e) {
                LOG.error("ImportHelper.setLinkData出错:", e);
            }
        } else if (Objects.equals(FieldTypeEnum.SERIALNO.getType(), linkAttr.getFieldType())) {
           value = paasFormDataEntityExt.getSerialNo();
        } else {
            value = targetData.getString(linkKey);
        }
        formDataObj.put(attr, value);
    }

    /**
     * 导出关联数据多选
     *
     * @param formDataObj
     * @param attr
     * @param exportLinkDataPojo
     * @param linkInfoPojo
     * @param corpid
     */
    private void setLinkDataMulti(JSONObject formDataObj, String attr, ExportLinkDataPojo exportLinkDataPojo, LinkInfoPojo linkInfoPojo, String corpid) {
        if (Objects.isNull(formDataObj.get(attr)) || !(formDataObj.get(attr) instanceof JSONArray)) {
            formDataObj.put(attr, "");
            return;
        }
        if (Objects.isNull(exportLinkDataPojo)) {
            return;
        }
        Map<String, PaasFormExplainEntity> formExplainMap = exportLinkDataPojo.getFormExplainMap();
        Map<String, WorkOrderExplainEntity> workOrderExplainMap = exportLinkDataPojo.getWorkOrderFormExplainMap();
        Map<String, PaasFormDataEntityExt> formDataMap = exportLinkDataPojo.getFormDataMap();
        if(linkInfoPojo == null || linkInfoPojo.getLinkKey() == null){
            formDataObj.put(attr, "");
            return;
        }
        String linkKey = linkInfoPojo.getLinkKey();
        Long formId = linkInfoPojo.getLinkFormId();
        if(formId == null){
            formDataObj.put(attr, "");
            return;
        }
        PaasFormExplainEntity linkForm = new PaasFormExplainEntity();
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), linkInfoPojo.getLinkBusinessType())) {
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainMap.get(formId.toString());
            if (Objects.isNull(workOrderExplainEntity)) {
                formDataObj.put(attr, "");
                return;
            }
            BeanUtil.copyProperties(workOrderExplainEntity, linkForm);
        } else {
            linkForm = formExplainMap.get(formId.toString());
        }
        if(linkForm == null){
            formDataObj.put(attr, "");
            return;
        }
        Map<String, FieldAttrEntity> linkExplainMap = ExplainUtil.getExplainMap(linkForm.getExplains(), linkKey);
        FieldAttrEntity linkAttr = linkExplainMap.get(linkKey);
        if(linkAttr == null){
            formDataObj.put(attr, "");
            return;
        }
        JSONArray jsonArray = formDataObj.getJSONArray(attr);
        Integer saasMark = linkInfoPojo.getLinkSaasMark();
        List<String> dataList = new ArrayList<>();
        for (Object o : jsonArray) {
            String key = o.toString();
            if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
                key = linkInfoPojo.getLinkBusinessType() + "_" +key;
            }
            PaasFormDataEntityExt paasFormDataEntityExt = formDataMap.get(key);
            if(paasFormDataEntityExt == null){
                continue;
            }
            JSONObject targetData = paasFormDataEntityExt.getData();
            if(targetData == null){
                continue;
            }
            if (Objects.equals(linkInfoPojo.getLinkBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(linkInfoPojo.getLinkKey(), ProductEnum.UNIT.getAttr())){
                try {
                    List<ItemPoJo> productItems = saasFormHelp.getProductItems(corpid);
                    linkAttr.setItems(productItems);
                } catch (XbbException e) {
                    e.printStackTrace();
                }
            }
            if (Objects.equals(FieldTypeEnum.COMBO.getType(), linkAttr.getFieldType()) || Objects.equals(FieldTypeEnum.RADIO_GROUP.getType(), linkAttr.getFieldType())) {
                Object comboObj = ItemUtil.analysisComboReturnStr(targetData, linkAttr);
                if (Objects.nonNull(comboObj) && StringUtil.isNotEmpty(comboObj.toString())){
                    dataList.add(comboObj.toString());
                }
            } else if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), linkAttr.getFieldType())) {
                try {
                    linkAttr.setItems(proFormHelp.getEditStageComboItems(linkAttr, linkInfoPojo.getLinkSaasMark(), linkInfoPojo.getLinkBusinessType(), corpid, linkInfoPojo.getLinkFormId(), targetData));
                    Object stageObj = ItemUtil.analysisComboReturnStr(targetData, linkAttr);
                    if (Objects.nonNull(stageObj) && StringUtil.isNotEmpty(stageObj.toString())){
                        dataList.add(stageObj.toString());
                    }
                } catch (XbbException e) {
                    LOG.error("ImportHelper.setLinkDataMulti出错:", e);
                }
            } else if (Objects.equals(FieldTypeEnum.SERIALNO.getType(), linkAttr.getFieldType())) {
                dataList.add(paasFormDataEntityExt.getSerialNo());
            } else {
                dataList.add(targetData.getString(linkKey));
            }
        }
        formDataObj.put(attr, String.join(StringConstant.COMMA, dataList));
    }

    /**
     * Description: 导出数据通用转换（工单关联数据提前解析了单独一个方法）
     * @param userMap
     * @param deptMap
     * @param paasFormDataEntityExt
     * @param phoneMap
     * @author 刘阳
     * @date 2019/7/23 5:30 PM
     * @since v1.0
     */
    public void formatWorkOrderData4Export(Map<String, Object> userMap, Map<String, Object> deptMap, PaasFormDataEntityExt paasFormDataEntityExt, JSONObject formDataObj, List<FieldAttrEntity> explainList, Map<Long, String> phoneMap, ExportLinkDataPojo exportLinkDataPojo, Integer businessType) {
        if (Objects.isNull(formDataObj.get(FieldTypeEnum.OWNERID.getAlias())) || (Objects.nonNull(formDataObj) && formDataObj.getJSONArray(FieldTypeEnum.OWNERID.getAlias()).isEmpty())) {
            formDataObj.put(FieldTypeEnum.OWNERID.getAlias(), "");
        }
        if (Objects.isNull(formDataObj.get(FieldTypeEnum.COUSERID.getAlias())) || ((Objects.nonNull(formDataObj) && formDataObj.getJSONArray(FieldTypeEnum.COUSERID.getAlias()).isEmpty()))) {
            formDataObj.put(FieldTypeEnum.COUSERID.getAlias(), "");
        }
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            String attr = fieldAttrEntity.getAttr();
            Integer fieldType = fieldAttrEntity.getFieldType();
            if (Objects.equals(fieldAttrEntity.getSaasAttr(), StringConstant.LAST_CONNECT_TIME_SAAS_ATTR) && Objects.equals(fieldType, FieldTypeEnum.DATETIME.getType())) {
                formDataObj.put(attr, TimeUtil.analysisLastConnectTime(formDataObj.getLong(attr)));
            } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_SINGLE.getType())) {
                setLinkBusinessSingleWorkOrderData(formDataObj, fieldAttrEntity, phoneMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_BUSINESS_MULTI.getType())) {
                setLinkBusinessMultiData(formDataObj, fieldAttrEntity);
            } else if (Objects.equals(fieldType, FieldTypeEnum.DATETIME.getType()) || Objects.equals(fieldType, FieldTypeEnum.UPDATETIME.getType()) || Objects.equals(fieldType, FieldTypeEnum.ENDTIME.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.ADDTIME.getType()) || Objects.equals(fieldType, FieldTypeEnum.CLOSETIME.getType())) {
                String fieldDateType = fieldAttrEntity.getDateType();
                setDateTimeData(paasFormDataEntityExt, formDataObj, attr, fieldDateType, fieldType);
            } else if (Objects.equals(fieldType, FieldTypeEnum.BIRTHDAY.getType())) {
                String birthdayFlagAttr = fieldAttrEntity.getLinkedText();
                setBirthdayData(formDataObj, attr, birthdayFlagAttr);
            } else if (Objects.equals(fieldType, FieldTypeEnum.ADDRESS.getType())) {
                setAddressData(formDataObj, attr);
            } else if (Objects.equals(fieldType, FieldTypeEnum.HREF.getType())) {
                setHrefData(formDataObj, attr);
            } else if (Objects.equals(fieldType, FieldTypeEnum.SINGLE_SUB_FORM.getType()) || Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
                setSubFormData(formDataObj, attr, fieldAttrEntity, userMap, deptMap, paasFormDataEntityExt, exportLinkDataPojo, businessType);
            } else if (Objects.equals(fieldType, FieldTypeEnum.SERIALNO.getType())) {
                formDataObj.put(attr, paasFormDataEntityExt.getSerialNo());
            } else if (Objects.equals(fieldType, FieldTypeEnum.OWNERID.getType()) || Objects.equals(fieldType, FieldTypeEnum.COUSERID.getType())) {
                try {
                    List<String> userIds = (List<String>)formDataObj.get(attr);
                    if (userIds.isEmpty()) {
                        formDataObj.put(attr, "");
                        continue;
                    }
                    StringBuilder value = new StringBuilder("");
                    for (String userId : userIds) {
                        if (userMap.containsKey(userId)) {
                            value.append(userMap.get(userId)).append(StringConstant.COMMA);
                        }
                    }
                    String valueString = value.toString();
                    if (StringUtil.isNotEmpty(valueString)) {
                        valueString = valueString.substring(0, valueString.length() - 1);
                    }
                    formDataObj.put(attr, valueString);
                } catch (Exception e) {
                    formDataObj.put(attr, "");
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.CREATORID.getType())) {
                formDataObj.put(attr, paasFormDataEntityExt.getCreatorId());
                //setUserOrDeptData(formDataObj, attr, userMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.USER_GROUP.getType())) {
                //setUserOrDeptGroupData(formDataObj, attr, userMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.USER.getType())) {
                //setUserOrDeptData(formDataObj, attr, userMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.DEPT.getType())) {
                //setUserOrDeptData(formDataObj, attr, deptMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.DEPT_GROUP.getType())) {
                //setUserOrDeptGroupData(formDataObj, attr, deptMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.DEPARTMENTID.getType())) {
                formDataObj.put(attr, paasFormDataEntityExt.getDepartmentId());
                setUserOrDeptData(formDataObj, attr, deptMap);
            } else if (Objects.equals(fieldType, FieldTypeEnum.COMBO_LINK_BUSINESS.getType())) {
                setComboLinkBusiness(formDataObj, attr);
            } else if (Objects.equals(fieldType, FieldTypeEnum.SWITCH.getType())) {
                setSwitchData(formDataObj, attr);
            } else if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldType)) {
                setLinkData(formDataObj, attr);
            }
        }
    }

    private void setLinkData(JSONObject formDataObj, String attr) {
        if (formDataObj.get(attr) instanceof List) {
            JSONArray jsonArray = formDataObj.getJSONArray(attr);
            if (CollectionsUtil.isNotEmpty(jsonArray)) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    formDataObj.put(attr, jsonObject.getString("name"));
                }
            }
        }
    }

    private void setLinkDataMulti(JSONObject formDataObj, String attr) {
        if (formDataObj.get(attr) instanceof List) {
            JSONArray jsonArray = formDataObj.getJSONArray(attr);
            if (CollectionsUtil.isNotEmpty(jsonArray)) {
                String temp;
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    temp = jsonObject.getString("name");
                }
            }
        }
    }


    private void setTemplateFieldData(JSONObject formDataObj, String attr) {
        // TODO: 2023/3/14 塞值
        Object isOpen = formDataObj.get(attr);
        List<Map> items = new ArrayList<>();
        Map<String,String> map = new HashMap<>();
        map.put("templateName","templateName");
        map.put("file","file");
        items.add(map);
        formDataObj.put(attr, items);
    }

    private void setSwitchData(JSONObject formDataObj, String attr) {
        Object isOpen = formDataObj.get(attr);
        if (Objects.nonNull(isOpen)) {
            if (Objects.equals(isOpen, 1) || Objects.equals(isOpen, OperateTypeEnum.YES.getName())) {
                formDataObj.put(attr, I18nMessageUtil.getMessage(OperateTypeEnum.YES.getName()));
            } else {
                formDataObj.put(attr, I18nMessageUtil.getMessage(OperateTypeEnum.NO.getName()));
            }
        }

    }

    private void setComboLinkBusiness(JSONObject formDataObj, String attr) {
        JSONArray linkBusinessArr = new JSONArray();
        JSONObject businessObj = new JSONObject();
        businessObj.put(ImportEnum.COMMUNICATE_BUSINESS_TYPE.getAttr(), formDataObj.getString(CommunicateBaseEnum.COMMUNICATE_BUSINESS_TYPE.getAttr()));
        businessObj.put(ImportEnum.COMMUNICATE_NAME.getAttr(), formDataObj.getString(CommunicateBaseEnum.COMMUNICATE_BUSINESS_HIDE.getAttr()));
        linkBusinessArr.add(businessObj);
        formDataObj.put(attr, linkBusinessArr);
    }

    private void setLinkBusinessMultiData(JSONObject formDataObj, FieldAttrEntity fieldAttrEntity) {
        String linkAttr = fieldAttrEntity.getLinkedText();
        if(linkAttr==null){
            return;
        }
        JSONArray linkBusinessMultiData = null;
        try {
            linkBusinessMultiData = formDataObj.getJSONArray(linkAttr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuilder needData = new StringBuilder();
        if (Objects.nonNull(linkBusinessMultiData) && !linkBusinessMultiData.isEmpty()) {
            for (int i = 0; i < linkBusinessMultiData.size(); i ++) {
                String singleData = linkBusinessMultiData.getString(i);
                needData.append(StringConstant.COMMA).append(singleData);
            }
            String data = needData.substring(1, needData.length());
            formDataObj.put(fieldAttrEntity.getAttr(), data);
        } else {
            formDataObj.put(fieldAttrEntity.getAttr(), "");
        }
    }

    public void formatDropDown4Export(List<FieldAttrEntityForImport> fieldAttrList, JSONObject formDataObj, FormDataListDTO formDataListDTO) {
        for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
            Integer fieldType = fieldAttrEntity.getFieldType();
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(fieldType, FieldTypeEnum.COMBO.getType()) || Objects.equals(fieldType, FieldTypeEnum.STAR.getType()) || Objects.equals(fieldType, FieldTypeEnum.RADIO_GROUP.getType())) {
                setDropDownListData(formDataObj, attr, fieldAttrEntity);
            } else if (Objects.equals(fieldType, FieldTypeEnum.CHECKBOX_GROUP.getType()) || Objects.equals(fieldType, FieldTypeEnum.COMBO_CHECK.getType())) {
                setDropDownGroupData(formDataObj, attr, fieldAttrEntity);
            } else if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType()) && !Objects.equals(attr.split("_")[0], FieldTypeEnum.SELECT_PRODUCT.getEsalias())
                 && !Objects.equals(fieldAttrEntity.getSaasAttr(), ProductEnum.STOCK.getSaasAttr())) {
                // 关联产品和库存
                List<FieldAttrEntityForImport> subExplainList = JSONArray.parseArray(JSON.toJSONString(fieldAttrEntity.getSubForm().getItems()), FieldAttrEntityForImport.class);
                for (FieldAttrEntityForImport subFieldAttr : subExplainList) {
                    Integer subFieldType = subFieldAttr.getFieldType();
                    String subAttr = subFieldAttr.getAttr();
                    // 这个居然不是引用，所以需要新加一个对象
                    JSONArray jsonArray = formDataObj.getJSONArray(attr);
                    if (Objects.isNull(jsonArray)) {
                        jsonArray = new JSONArray();
                    }
                    JSONArray tempArray = new JSONArray();
                    if (Objects.equals(subFieldType, FieldTypeEnum.COMBO.getType()) || Objects.equals(subFieldType, FieldTypeEnum.STAR.getType())
                            || Objects.equals(subFieldType, FieldTypeEnum.RADIO_GROUP.getType())) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            setDropDownListData(jsonObject, subAttr, subFieldAttr);
                            tempArray.add(jsonObject);
                        }
                        if (tempArray.isEmpty()) {
                            formDataObj.put(attr, "");
                        } else {
                            formDataObj.put(attr, tempArray);
                        }
                    } else if (Objects.equals(subFieldType, FieldTypeEnum.CHECKBOX_GROUP.getType()) || Objects.equals(subFieldType, FieldTypeEnum.COMBO_CHECK.getType())) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            setDropDownGroupData(jsonObject, subAttr, subFieldAttr);
                            tempArray.add(jsonObject);
                        }
                        if (tempArray.isEmpty()) {
                            formDataObj.put(attr, "");
                        } else {
                            formDataObj.put(attr, tempArray);
                        }
                    } else if (Objects.equals(subFieldType, FieldTypeEnum.SWITCH.getType())) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            setSwitchData(jsonObject, subAttr);
                            tempArray.add(jsonObject);
                        }
                        if (tempArray.isEmpty()) {
                            formDataObj.put(attr, "");
                        } else {
                            formDataObj.put(attr, tempArray);
                        }
                    }
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.LABEL.getType())){
                setLabelDownListData(formDataObj, attr, fieldAttrEntity);
            } else if (Objects.equals(fieldType, FieldTypeEnum.STAGE_THRUSTER.getType())) {
                //阶段推进器数据格式化
                setStageData(formDataObj, fieldAttrEntity, formDataListDTO);
            }
        }
    }

    /**
     * 处理阶段推进器的数据
     * @param formDataObj
     * @param fieldAttrEntity
     * @param formDataListDTO
     */
    private void setStageData(JSONObject formDataObj, FieldAttrEntity fieldAttrEntity, FormDataListDTO formDataListDTO) {
        String attr = fieldAttrEntity.getAttr();
        Integer saasMark = formDataListDTO.getSaasMark();
        Integer businessType = formDataListDTO.getBusinessType();
        String corpid = formDataListDTO.getCorpid();
        Long formId = formDataListDTO.getFormId();
        try {
            String dropDownData = formDataObj.getString(attr);

            //处理表单解释的itemPojo，因为阶段推进器存在多版本，所以不能在前面的统一处理表单解释处处理
            if (StringUtil.isEmpty(dropDownData)) {
                formDataObj.put(attr, "");
                return;
            }
            List<ItemPoJo> itemPoJoList = proFormHelp.getEditStageComboItems(fieldAttrEntity, saasMark, businessType, corpid, formId, formDataObj);
            if (CollectionsUtil.isEmpty(itemPoJoList)) {
                formDataObj.put(attr, "");
                return;
            } else {
                for (ItemPoJo itemPoJo : itemPoJoList) {
                    if (Objects.equals(itemPoJo.getValue().toString(), dropDownData)) {
                        formDataObj.put(attr, itemPoJo.getText());
                        break;
                    }
                }
            }
        } catch (Exception e) {
            formDataObj.put(attr, "");
        }
    }

    /**
     * 标签处理
     * @param formDataObj
     * @param attr
     * @param fieldAttrEntity
     */
    private void setLabelDownListData(JSONObject formDataObj, String attr, FieldAttrEntity fieldAttrEntity) {
        try {
            JSONArray dropDownData = formDataObj.getJSONArray(attr);
            if (dropDownData == null || dropDownData.isEmpty()) {
                formDataObj.put(attr, "");
                return;
            }

            List<ItemPoJo> itemPoJoList = fieldAttrEntity.getItems();
            StringBuilder stringBuilder = new StringBuilder();
            for (ItemPoJo itemPoJo : itemPoJoList) {
                for (int i = 0; i < dropDownData.size(); i++) {
                    String value = dropDownData.getString(i);
                    if (Objects.equals(itemPoJo.getValue().toString(), value)) {
                        stringBuilder.append(itemPoJo.getText()).append(StringConstant.COMMA);
                        break;
                    }
                }
            }
            if (stringBuilder.length() == 0) {
                for (int i = 0; i < dropDownData.size(); i++) {
                    stringBuilder.append(dropDownData.getString(i)).append(StringConstant.COMMA);
                }
            }
            formDataObj.put(attr,  stringBuilder.substring(0, stringBuilder.length() - 1));
        } catch (Exception e) {
            formDataObj.put(attr, "");
        }
    }

    public void workOrderFormatDropDown4Export(List<FieldAttrEntityForImport> fieldAttrList, JSONObject formDataObj) {
        for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
            Integer fieldType = fieldAttrEntity.getFieldType();
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(fieldType, FieldTypeEnum.COMBO.getType()) || Objects.equals(fieldType, FieldTypeEnum.STAR.getType()) || Objects.equals(fieldType, FieldTypeEnum.RADIO_GROUP.getType())) {
                setDropDownListData(formDataObj, attr, fieldAttrEntity);
            } else if (Objects.equals(fieldType, FieldTypeEnum.CHECKBOX_GROUP.getType()) || Objects.equals(fieldType, FieldTypeEnum.COMBO_CHECK.getType())) {
                setWorkOrderDropDownGroupData(formDataObj, attr);
            } else if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType()) && !Objects.equals(attr.split("_")[0], FieldTypeEnum.SELECT_PRODUCT.getEsalias())
                    && !Objects.equals(fieldAttrEntity.getSaasAttr(), ProductEnum.STOCK.getSaasAttr())) {
                // 关联产品和库存
                List<FieldAttrEntityForImport> subExplainList = JSONArray.parseArray(JSON.toJSONString(fieldAttrEntity.getSubForm().getItems()), FieldAttrEntityForImport.class);
                for (FieldAttrEntityForImport subFieldAttr : subExplainList) {
                    Integer subFieldType = subFieldAttr.getFieldType();
                    String subAttr = subFieldAttr.getAttr();
                    // 这个居然不是引用，所以需要新加一个对象
                    JSONArray jsonArray = formDataObj.getJSONArray(attr);
                    if (Objects.isNull(jsonArray)) {
                        jsonArray = new JSONArray();
                    }
                    JSONArray tempArray = new JSONArray();
                    if (Objects.equals(subFieldType, FieldTypeEnum.COMBO.getType()) || Objects.equals(subFieldType, FieldTypeEnum.STAR.getType())
                            || Objects.equals(subFieldType, FieldTypeEnum.RADIO_GROUP.getType())) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            setDropDownListData(jsonObject, subAttr, subFieldAttr);
                            tempArray.add(jsonObject);
                        }
                        if (tempArray.isEmpty()) {
                            formDataObj.put(attr, "");
                        } else {
                            formDataObj.put(attr, tempArray);
                        }
                    } else if (Objects.equals(subFieldType, FieldTypeEnum.CHECKBOX_GROUP.getType()) || Objects.equals(subFieldType, FieldTypeEnum.COMBO_CHECK.getType())) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            setDropDownGroupData(jsonObject, subAttr, subFieldAttr);
                            tempArray.add(jsonObject);
                        }
                        if (tempArray.isEmpty()) {
                            formDataObj.put(attr, "");
                        } else {
                            formDataObj.put(attr, tempArray);
                        }
                    } else if (Objects.equals(subFieldType, FieldTypeEnum.SWITCH.getType())) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            setSwitchData(jsonObject, subAttr);
                            tempArray.add(jsonObject);
                        }
                        if (tempArray.isEmpty()) {
                            formDataObj.put(attr, "");
                        } else {
                            formDataObj.put(attr, tempArray);
                        }
                    }
                }
            }
        }
    }


    /**
     * 导出时，将下拉框的值转换成具体的文本信息
     * @param formDataObj
     * @param attr
     * @param fieldAttrEntity
     */
    private void setDropDownListData(JSONObject formDataObj, String attr, FieldAttrEntity fieldAttrEntity) {
        try {
            String dropDownData = formDataObj.getString(attr);
            if (StringUtil.isEmpty(dropDownData)) {
                formDataObj.put(attr, "");
                return;
            }
            // 下拉选项删除后导出为数字的问题
            boolean deleteCheck = ItemUtil.isDeleteCheck(dropDownData, fieldAttrEntity);
            if (deleteCheck) {
                formDataObj.put(attr, "");
            } else if (formDataObj.get(attr) instanceof ItemPoJo) {
                formDataObj.put(attr, ItemUtil.parseItemPoJoFromFormData2String(formDataObj, attr, ""));
                return;
            } else {
                formDataObj.put(attr, dropDownData);
            }
            List<ItemPoJo> itemPoJoList = fieldAttrEntity.getItems();
            for (ItemPoJo itemPoJo : itemPoJoList) {
                if (Objects.equals(itemPoJo.getValue().toString(), dropDownData)) {
                    formDataObj.put(attr, itemPoJo.getText());
                    break;
                }
            }
        } catch (Exception e) {
            formDataObj.put(attr, "");
        }
    }

    /**
     * 导出时，将下拉框复选值转换成具体的文本信息
     * @param formDataObj
     * @param attr
     * @param fieldAttrEntity
     */
    private void setDropDownGroupData(JSONObject formDataObj, String attr, FieldAttrEntity fieldAttrEntity) {
        try {
            JSONArray dropDownData = formDataObj.getJSONArray(attr);
            if (dropDownData == null || dropDownData.isEmpty()) {
                formDataObj.put(attr, "");
                return;
            }

            List<Object> valueList = ItemUtil.analysisComboReturnList(formDataObj, fieldAttrEntity);

            formDataObj.put(attr, StringUtils.join(valueList, StringConstant.COMMA));
        } catch (Exception e) {
            formDataObj.put(attr, "");
        }
    }

    /**
     * Description: 导出时，将下拉框复选值转换成具体的文本信息(工单)
     * @param formDataObj
     * @param attr
     * @author 刘阳
     * @date 2019/8/23 9:39 AM
     * @since v1.0
     */
    private void setWorkOrderDropDownGroupData(JSONObject formDataObj, String attr) {
        try {
            Object dropDownData = formDataObj.get(attr);
            if (dropDownData == null) {
                formDataObj.put(attr, "");
                return;
            }
        } catch (Exception e) {
            formDataObj.put(attr, "");
        }
    }


    private void setUserOrDeptGroupData(JSONObject formDataObj, String attr, Map<String,Object> userMap) {
        try {
            JSONArray userArr = formDataObj.getJSONArray(attr);
            if (Objects.isNull(userArr)) {
                formDataObj.put(attr, "");
                return;
            }
            List<String> userOrDeptList = userArr.toJavaList(String.class);
            String userName = "";
            for (String userId : userOrDeptList) {
                if (userMap.containsKey(userId)) {
                    userName += userMap.get(userId) + StringConstant.COMMA;
                }
            }
            if (userName.endsWith(StringConstant.COMMA)) {
                userName = userName.substring(0, userName.length() - 1);
            }
            formDataObj.put(attr, userName);
        } catch (Exception e) {
            formDataObj.put(attr, "");
        }
    }

    private void setUserOrDeptData(JSONObject formDataObj, String attr, Map<String, Object> userMap) {
        try {
            String userId = formDataObj.getString(attr);
            formDataObj.put(attr, "");
            if (StringUtil.isEmpty(userId)) {
                return;
            }
            formDataObj.put(attr, userMap.getOrDefault(userId, ""));
        } catch (Exception e) {
            formDataObj.put(attr, "");
        }
    }

    /**
     * 孤独子表单转换
     * @param formDataObj
     * @param attr
     */
    private void setSubFormData(JSONObject formDataObj, String attr, FieldAttrEntity fieldAttrEntity, Map<String, Object> userMap,
                                Map<String, Object> deptMap, PaasFormDataEntityExt paasFormDataEntityExt, ExportLinkDataPojo exportLinkDataPojo, Integer businessType) {
        List<? extends FieldAttrEntity> fieldAttrEntityList = fieldAttrEntity.getSubForm().getItems();
        JSONArray jsonArray;
        try {
            jsonArray  = formDataObj.getJSONArray(attr);
        } catch (Exception e) {
            LOG.error("ImportHelper.setSubFormData execute error ", e);
            jsonArray = new JSONArray();
        }

        JSONArray newJsonArr = new JSONArray();
        if (Objects.nonNull(jsonArray) && !jsonArray.isEmpty()) {
            for (int i = 0; i < jsonArray.size(); i ++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                formatCommonData4Export(userMap, deptMap, paasFormDataEntityExt, jsonObject, fieldAttrEntityList, null, exportLinkDataPojo, businessType, null);
                newJsonArr.add(jsonObject);
            }
        }
        formDataObj.put(attr, newJsonArr);
    }

    /**
     * 超链接转换
     * @param formDataObj
     * @param attr
     */
    private void setHrefData(JSONObject formDataObj, String attr) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        JSONObject hrefObject = formDataObj.getJSONObject(attr);
        if (hrefObject != null) {
            String name = hrefObject.getString("name");
            String value = hrefObject.getString("value");
            jsonObject.put(ImportEnum.HREF_TEXT.getAttr(), name);
            jsonObject.put(ImportEnum.HREF_LINK.getAttr(), value);
        }
        jsonArray.add(jsonObject);
        formDataObj.put(attr, jsonArray);
    }

    /**
     * 地址转换
     * @param formDataObj
     * @param attr
     */
    private void setAddressData(JSONObject formDataObj, String attr) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        JSONObject addressObject = formDataObj.getJSONObject(attr);
        if (addressObject != null) {
            String address = addressObject.getString(AddressEnum.ADDRESS.getAlias());
            String province = addressObject.getString(AddressEnum.PROVINCE.getAlias());
            String city = addressObject.getString(AddressEnum.CITY.getAlias());
            String district = addressObject.getString(AddressEnum.DISTRICT.getAlias());
            jsonObject.put(ImportEnum.PROVINCE.getAttr(), province);
            jsonObject.put(ImportEnum.CITY.getAttr(), city);
            jsonObject.put(ImportEnum.AREA.getAttr(), district);
            jsonObject.put(ImportEnum.DETAIL_ADDRESS.getAttr(), address);
        }
        jsonArray.add(jsonObject);
        formDataObj.put(attr, jsonArray);
    }

    private void setLocationData(JSONObject formDataObj, String attr) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        JSONObject locationObject = formDataObj.getJSONObject(attr);
        if (locationObject != null) {
            String address = locationObject.getString(AddressEnum.ADDRESS.getAlias());
            String province = locationObject.getString(AddressEnum.PROVINCE.getAlias());
            String city = locationObject.getString(AddressEnum.CITY.getAlias());
            String district = locationObject.getString(AddressEnum.DISTRICT.getAlias());
            jsonObject.put(ImportEnum.PROVINCE.getAttr(), province);
            jsonObject.put(ImportEnum.CITY.getAttr(), city);
            jsonObject.put(ImportEnum.AREA.getAttr(), district);
            jsonObject.put(ImportEnum.DETAIL_ADDRESS.getAttr(), address);
        }
        jsonArray.add(jsonObject);
        formDataObj.put(attr, jsonArray);
    }

    /**
     * 生日转换
     * @param formDataObj
     * @param attr
     * @param flagAttr
     *
     */
    private void setBirthdayData(JSONObject formDataObj, String attr, String flagAttr) {
        Integer isLunarBirthdayShown = formDataObj.getInteger(flagAttr);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        String birthday = formDataObj.getString(attr);
        if (DateTimeUtil.isSDFDate(birthday)) {
            jsonObject.put(ImportEnum.BIRTHDAY_FLAG.getAttr(), isLunarBirthdayShown);
            jsonObject.put(ImportEnum.BIRTHDAY.getAttr(), birthday);
            jsonArray.add(jsonObject);
        }
        formDataObj.put(attr, jsonArray);
    }

    /**
     * 关联业务单选转换
     * @param formDataObj
     * @param fieldAttrEntity
     * @param phoneMap
     */
    private void setLinkBusinessSingleData(JSONObject formDataObj, FieldAttrEntity fieldAttrEntity, Map<Long, String> phoneMap) {
        String linkAttr = fieldAttrEntity.getLinkedText();
        if(linkAttr==null){
            return;
        }
        String linkBusinessSingleData = formDataObj.getString(linkAttr);
        if (Objects.equals(fieldAttrEntity.getLinkedType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())
                || Objects.equals(fieldAttrEntity.getLinkedType(), XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode())) {
            JSONArray customerArr = new JSONArray();
            JSONObject customerObj = new JSONObject();
            if (Objects.nonNull(phoneMap)) {
                Long customerId;
                try {
                    customerId = formDataObj.getLong(fieldAttrEntity.getAttr());
                    if (customerId == null) {
                        customerId = 0L;
                    }
                } catch (Exception e) {
                    customerId = 0L;
                }
                customerObj.put(ImportEnum.LINK_CUSTOMER_PHONE.getAttr(),phoneMap.getOrDefault(customerId, ""));
            }
            customerObj.put(ImportEnum.LINK_CUSTOMER_NAME.getAttr(), linkBusinessSingleData);
            customerArr.add(customerObj);
            formDataObj.put(fieldAttrEntity.getAttr(), customerArr);
        } else {
            formDataObj.put(fieldAttrEntity.getAttr(), linkBusinessSingleData);
        }
    }

    /**
     * Description: 工单关联业务单选转化
     * @param formDataObj
     * @param fieldAttrEntity
     * @param phoneMap
     * @author 刘阳
     * @date 2019/7/23 6:28 PM
     * @since v1.0
     */
    private void setLinkBusinessSingleWorkOrderData(JSONObject formDataObj, FieldAttrEntity fieldAttrEntity, Map<Long, String> phoneMap) {
        String linkAttr = fieldAttrEntity.getLinkedText();
        String linkBusinessSingleData = formDataObj.getString(linkAttr);
        if (Objects.equals(fieldAttrEntity.getLinkedType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            JSONArray customerArr = new JSONArray();
            JSONObject customerObj = new JSONObject();
            String name = null;
            Long customerId = 0L;
            try {
                JSONArray jsonArray = formDataObj.getJSONArray(WorkOrderEnum.LINK_CUSTOMER.getAttr());
                if (jsonArray != null && jsonArray.size() > 0) {
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    name = jsonObject.getString(BasicConstant.NAME);
                    customerId = jsonObject.getLong(BasicConstant.ID);
                }
            } catch (Exception e) {
                name = null;
                customerId = 0L;
            }
            customerObj.put(ImportEnum.LINK_CUSTOMER_NAME.getAttr(), name);
            customerObj.put(ImportEnum.LINK_CUSTOMER_PHONE.getAttr(),phoneMap.getOrDefault(customerId, ""));
            customerArr.add(customerObj);
            formDataObj.put(fieldAttrEntity.getAttr(), customerArr);
        } else if (Objects.equals(fieldAttrEntity.getLinkedType(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
            //脏数据（奥琦玮）没有销售机会编号，兼容它这种蛇皮情况
            Object object = formDataObj.get(WorkOrderEnum.LINK_OPPORTUNITY.getAttr());
            String name = null;
            if (object instanceof JSONArray) {
                JSONArray jsonArray = formDataObj.getJSONArray(WorkOrderEnum.LINK_OPPORTUNITY.getAttr());
                if (jsonArray != null && jsonArray.size() > 0) {
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    name = jsonObject.getString("name");
                }
            } else {
                name = "";
            }
            formDataObj.put(fieldAttrEntity.getAttr(), name);
        } else if (Objects.equals(fieldAttrEntity.getLinkedType(), XbbRefTypeEnum.CONTRACT.getCode())) {
            JSONArray jsonArray = formDataObj.getJSONArray(WorkOrderEnum.LINK_CONTRACT.getAttr());
            String name = null;
            if (jsonArray != null && jsonArray.size() > 0) {
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                name = jsonObject.getString("name");
            }
            formDataObj.put(fieldAttrEntity.getAttr(), name);
        } else if (Objects.equals(fieldAttrEntity.getLinkedType(), XbbRefTypeEnum.CONTACT.getCode())) {
            JSONArray jsonArray = formDataObj.getJSONArray(WorkOrderEnum.LINK_CONTACT.getAttr());
            String name = null;
            if (jsonArray != null && jsonArray.size() > 0) {
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                name = jsonObject.getString("name");
            }
            formDataObj.put(fieldAttrEntity.getAttr(), name);
        } else {
            formDataObj.put(fieldAttrEntity.getAttr(), linkBusinessSingleData);
        }
    }

    private void setDateTimeData(PaasFormDataEntityExt paasFormDataEntityExt, JSONObject formDataObj, String attr, String fieldDateType, Integer fieldType) {
        SimpleDateFormat dateFormat;
        try {
            dateFormat = new SimpleDateFormat(fieldDateType);
        } catch (Exception e) {
            dateFormat = DateTimeUtil.SDFDate;
        }
        try {
            Long timeEpochSecond;
            if (Objects.equals(fieldType, FieldTypeEnum.ADDTIME.getType())) {
                timeEpochSecond = paasFormDataEntityExt.getAddTime();
            } else if (Objects.equals(fieldType, FieldTypeEnum.UPDATETIME.getType())) {
                timeEpochSecond = paasFormDataEntityExt.getUpdateTime();
            } else {
                timeEpochSecond = formDataObj.getLong(attr);
            }
            // 13位时间戳转换
            if (Objects.nonNull(timeEpochSecond) && timeEpochSecond.toString().length() == 13){
                timeEpochSecond = timeEpochSecond/1000;
            }
            String formatDateTime = DateTimeUtil.getStringEpochSecond(timeEpochSecond, dateFormat);
            formDataObj.put(attr, formatDateTime);
        } catch (Exception e) {
            formDataObj.put(attr, "");
        }
    }

    private void setLinkBusinessSingleData(JSONObject formDataObj, String attr) {
        try {
            String linkBusinessSingleData = formDataObj.getString(attr);
            if (StringUtil.isEmpty(linkBusinessSingleData)) {
                formDataObj.put(attr, "");
                return;
            }
            JSONArray customerArray = JSON.parseArray(linkBusinessSingleData);
            if (Objects.nonNull(customerArray) && !customerArray.isEmpty()) {
                JSONObject customerObj = customerArray.getJSONObject(0);
                formDataObj.put(attr, customerObj.getString(StringConstant.SAAS_LINK_BUSINESS_NAME));
            }
        } catch (Exception e) {
            formDataObj.put(attr, "");
        }
    }

    public void checkImportData(List<CellValuePojo> cellValueList, List<CellTitlePojo> titlePojoList,
                                List<FieldAttrEntityForImport> fieldAttrEntityForImportList, String parentTitle) throws XbbException {
        // 子表单的值后校验
        for (FieldAttrEntityForImport fieldAttr : fieldAttrEntityForImportList) {
            Integer fieldType = fieldAttr.getFieldType();
            Integer required = fieldAttr.getRequired();
            String attrName = fieldAttr.getAttrName();
            Integer columnIndex = getColumnIndexByTitle(titlePojoList, attrName, parentTitle);
            Object cellValue = getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.equals(required, 1)) {
                if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
                    List<FieldAttrEntityForImport> subExplainList = JSONArray.parseArray(
                            JSON.toJSONString(fieldAttr.getSubForm().getItems()), FieldAttrEntityForImport.class);
                    checkImportData(cellValueList, titlePojoList, subExplainList, attrName);
                } else {
                    if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                        throw new XbbException(ImportErrorCodeEnum.API_ERROR_235007.getCode(), ImportErrorCodeEnum.API_ERROR_235007.getMsg(), (Objects.nonNull(parentTitle) ? parentTitle : "") + attrName);
                    }
                }
            }
        }
    }

    /**
     * 校验数字类型及数字精度
     *
     * @param
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-09-24 17:05
     * @since v1.0
     * @version v1.0
     */
    public void checkImportDataForNum(List<CellValuePojo> cellValueList, List<CellTitlePojo> titlePojoList,
                                List<FieldAttrEntityForImport> fieldAttrEntityForImportList, String parentTitle, String corpid, String userId, Integer businessType) throws XbbException {
        // 子表单的值后校验
        for (FieldAttrEntityForImport fieldAttr : fieldAttrEntityForImportList) {
            Integer fieldType = fieldAttr.getFieldType();
            Integer required = fieldAttr.getRequired();
            String attrName = fieldAttr.getAttrName();
            Integer columnIndex = getColumnIndexByTitle(titlePojoList, attrName, parentTitle);
            Object cellValue = getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
                List<FieldAttrEntityForImport> subExplainList = JSONArray.parseArray(
                        JSON.toJSONString(fieldAttr.getSubForm().getItems()), FieldAttrEntityForImport.class);

                // 子表单是产品时，获取精度
                boolean productFlag = false;
                for (FieldAttrEntityForImport entity : subExplainList) {
                    if (Objects.equals(SelectProductEnum.PRODUCT_NAME.getSaasAttr(), entity.getSaasAttr())) {
                        productFlag = true;
                        break;
                    }
                }
                if (productFlag) {
                    proFormHelp.setProductAccuracy(fieldAttr, corpid, userId);
                    subExplainList = JSONArray.parseArray(
                            JSON.toJSONString(fieldAttr.getSubForm().getItems()), FieldAttrEntityForImport.class);
                }

                checkImportDataForNum(cellValueList, titlePojoList, subExplainList, attrName, corpid, userId, businessType);
            } else if(Objects.equals(FieldTypeEnum.NUM.getType(), fieldType)) {
                // 数字精度
                int accuracy = Objects.isNull(fieldAttr.getAccuracy()) ? 0 : fieldAttr.getAccuracy();
                if(Objects.nonNull(cellValue) && StringUtil.isNotEmpty(cellValue.toString())) {
                    int dcimalDigits = 0;
                    //多单位产品导入时  单价栏拆开校验精度
                    if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType) && Objects.equals(ProductEnum.PRICE.getAttr(), fieldAttr.getAttr()) && (cellValue.toString().contains("|") || cellValue.toString().contains("｜"))){
                        String[] prices = cellValue.toString().replace("｜", "|").split("\\|");
                        for (int i = 0; i < prices.length; i++) {
                            cellValue = prices[i];
                            try {
                                String balanceStr = new BigDecimal(cellValue.toString()).toString();
                                int indexOf = balanceStr.indexOf(StringConstant.POINT);
                                if (indexOf > 0) {
                                    dcimalDigits = balanceStr.length() - 1 - indexOf;
                                }
                            } catch (NumberFormatException e) {
                                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235007.getCode(), (Objects.nonNull(parentTitle) ? parentTitle : "") + attrName + I18nMessageUtil.getMessage(I18nStringConstant.NOT_NUMERIC_TYPE));
                            }
                            if (dcimalDigits > accuracy) {
                                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015.getCode(), (Objects.nonNull(parentTitle) ? parentTitle : "") + attrName + I18nMessageUtil.getMessage(I18nStringConstant.DECIMAL_PRECISION_EXCEEDS_SET_VALUE));
                            }
                        }
                    }else {
                        try {
                            String balanceStr = new BigDecimal(cellValue.toString()).toString();
                            int indexOf = balanceStr.indexOf(StringConstant.POINT);
                            if (indexOf > 0) {
                                dcimalDigits = balanceStr.length() - 1 - indexOf;
                            }
                        } catch (NumberFormatException e) {
                            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235007.getCode(), (Objects.nonNull(parentTitle) ? parentTitle : "") + attrName + I18nMessageUtil.getMessage(I18nStringConstant.NOT_NUMERIC_TYPE));
                        }
                        if (dcimalDigits > accuracy) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015.getCode(), (Objects.nonNull(parentTitle) ? parentTitle : "") + attrName + I18nMessageUtil.getMessage(I18nStringConstant.DECIMAL_PRECISION_EXCEEDS_SET_VALUE));
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据用户输入的单价 分割为数组
     * @param priceStr
     * @return 单价数组
     * @throws XbbException
     */
    public List<Double> checkImportDataForPirce(String priceStr) throws XbbException{
        List<Double> unitList = new ArrayList<>();
        if (!StringUtil.isEmpty(priceStr)){
            //兼容用户输入的中文 "｜" 和英文的 "｜"
            String replacePriceStr = priceStr.replace('｜', '|');
            String[] price = replacePriceStr.split("\\|");
            for (int i = 0; i < price.length; i++) {
                if (!StringUtil.isDigital(price[i])){
                    throw new XbbException(ProductErrorCodeEnum.API_ERROR_205098);
                }else {
                    unitList.add(Double.valueOf(price[i]));
                }
            }
            return unitList;
        }
        return unitList;
    }

    /**
     *单价自动填充
     * @param excelPriceList 导入已输入的单价数组
     * @param unitProportionList 系统中单位组中的单位比例
     * @return 自动填充后的单价数组
     */
    public List<Double> unitConversion(List<Double> excelPriceList, List<Double> unitProportionList){
        if(excelPriceList.isEmpty()){
            for (int i = 0; i < unitProportionList.size(); i++) {
                excelPriceList.add(0d);
            }
            return excelPriceList;
        }else {
            //用户输入的第一个单价
            Double firstPrice = excelPriceList.get(0);
            if (excelPriceList.size() > unitProportionList.size()) {
                excelPriceList = excelPriceList.subList(0, unitProportionList.size());
            } else {
                for (int i = 0; i < unitProportionList.size(); i++) {
                    if (i > excelPriceList.size() - 1) {
                        excelPriceList.add(Arith.mul(unitProportionList.get(i), firstPrice));
                        if (unitProportionList.size() == excelPriceList.size()) {
                            break;
                        }
                    }
                }
            }
            return excelPriceList;
        }
    }

    /**
     * 多单位导入 单价拼成新建格式
     * @param priceList 单价list
     * @param groupId 单位组id
     * @return 新建产品所需要的单价格式
     * @throws XbbException
     */
    public List<MultiUnitPricePoJo> priceRate(List<Double> priceList, Long groupId, Map<Long, List<UnitItemPoJo>> groupItemsMap) throws XbbException {
        List<MultiUnitPricePoJo> priceRateList = new ArrayList<>();
        List<UnitItemPoJo> unitItemPoJos = groupItemsMap.get(groupId);
        for (int i = 0; i < unitItemPoJos.size(); i++) {
            MultiUnitPricePoJo multiUnitPricePoJo = new MultiUnitPricePoJo();
            multiUnitPricePoJo.setText(unitItemPoJos.get(i).getText());
            multiUnitPricePoJo.setValue(unitItemPoJos.get(i).getValue());
            multiUnitPricePoJo.setRate(priceList.get(i));
            priceRateList.add(multiUnitPricePoJo);
        }
        return priceRateList;
    }


    /**
     * 格式化关联客户返回客户id
     *
     * @param titlePojoList
     * @param dataJson
     * @param rowValueList
     * @param fieldAttr
     * @return
     * @throws XbbException
     */
    public Long formatLinkCustomer2CustomerId(List<CellTitlePojo> titlePojoList, JSONObject dataJson, List<List<CellValuePojo>> rowValueList, FieldAttrEntityForImport fieldAttr) throws XbbException {
        Long linkCustomerId;
        String uniqueKey = getCustomerUniqueKey(rowValueList, titlePojoList, fieldAttr.getAttrName());
        if (uniqueKey.isEmpty()) {
            if (Objects.equals(fieldAttr.getRequired(), 1)) {
                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235007.getCode(), ImportErrorCodeEnum.API_ERROR_235007.getMsg(), fieldAttr.getAttrName());
            }
            return 0L;
        }
        Map<String, Object> linkBusinessMap = fieldAttr.getLinkBusinessMap();
        List<String> repeatErrorKey = fieldAttr.getRepeatErrorKey();
        if (repeatErrorKey.contains(uniqueKey)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ImportConstant.HAVE_SAME_CUSTOMER);
        }
        if (linkBusinessMap.containsKey(uniqueKey)) {
            PaasFormDataEntityExt paasFormDataEntityExt = (PaasFormDataEntityExt)linkBusinessMap.get(uniqueKey);
            JSONArray linkBusinessArr = new JSONArray();
            JSONObject linkCustomerObj = new JSONObject();
            linkCustomerId = paasFormDataEntityExt.getId();
            linkCustomerObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, linkCustomerId);
            linkCustomerObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, paasFormDataEntityExt.getData().getString(CustomerManagementEnum.NAME.getAttr()));
            linkBusinessArr.add(linkCustomerObj);
            dataJson.put(fieldAttr.getAttr(), linkBusinessArr);
        } else {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_EXISTS_IN_SYSTEM, fieldAttr.getAttrName());
        }
        return linkCustomerId;
    }

    /**
     * 格式化关联线索返回线索id
     *
     * @param titlePojoList
     * @param dataJson
     * @param rowValueList
     * @param fieldAttr
     * @return
     * @throws XbbException
     */
    public Long formatLinkClue2ClueId(List<CellTitlePojo> titlePojoList, JSONObject dataJson, List<List<CellValuePojo>> rowValueList, FieldAttrEntityForImport fieldAttr) throws XbbException {
        Long linkClueId;
        String uniqueKey = "";
        List<CellValuePojo> cellValueList = rowValueList.get(0);
        String parentTitle = fieldAttr.getAttrName();
        Integer businessNameIndex = getColumnIndexByTitle(titlePojoList, ImportEnum.COMMUNICATE_NAME.getAttrName(), parentTitle);
        Integer businessTypeIndex = getColumnIndexByTitle(titlePojoList, ImportEnum.COMMUNICATE_BUSINESS_TYPE.getAttrName(), parentTitle);
        Object nameCellValue = getValueByColumnIndex(cellValueList, businessNameIndex);
        Object typeCellValue = getValueByColumnIndex(cellValueList, businessTypeIndex);
        boolean nameNotEmpty = Objects.nonNull(nameCellValue) && StringUtil.isNotEmpty(nameCellValue.toString());
        boolean typeNotEmpty = Objects.nonNull(typeCellValue) && StringUtil.isNotEmpty(typeCellValue.toString());
        if (typeNotEmpty && Objects.equals(typeCellValue, XbbRefTypeEnum.CLUE.getName()) && nameNotEmpty){
            uniqueKey = uniqueKey + nameCellValue.toString().trim();
        }
        // 线索名称为空
        if (uniqueKey.isEmpty()) {
            if (Objects.equals(fieldAttr.getRequired(), 1)) {
                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235007.getCode(), ImportErrorCodeEnum.API_ERROR_235007.getMsg(), fieldAttr.getAttrName());
            }
            return 0L;
        }
        // 线索名验重
        Map<String, Object> linkBusinessMap = fieldAttr.getLinkBusinessMap();
        List<String> repeatErrorKey = fieldAttr.getRepeatErrorKey();
        if (repeatErrorKey.contains(uniqueKey)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ImportConstant.HAVE_SAME_CLUE);
        }

        if (linkBusinessMap.containsKey(uniqueKey)) {
            PaasFormDataEntityExt paasFormDataEntityExt = (PaasFormDataEntityExt)linkBusinessMap.get(uniqueKey);
            JSONObject linkClueObj = new JSONObject();
            linkClueId = paasFormDataEntityExt.getId();
            linkClueObj.put(StringConstant.SAAS_LINK_BUSINESS_LINK_TYPE, XbbRefTypeEnum.CLUE.getCode());
            linkClueObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, linkClueId);
            linkClueObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, paasFormDataEntityExt.getData().getString(CustomerManagementEnum.NAME.getAttr()));
            dataJson.put(fieldAttr.getAttr(), linkClueObj);
        } else {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_EXISTS_IN_SYSTEM, XbbRefTypeEnum.CLUE.getName());
        }

        return linkClueId;
    }

    /**
     * 格式化关联供应商返回供应商id
     *
     * @param dataJson
     * @param fieldAttr
     * @return
     * @throws XbbException
     */
    public Long formatSuppplier2SupplierId(String cellValue, JSONObject dataJson, FieldAttrEntityForImport fieldAttr) throws XbbException {
        Long linkSupplierId = null;
        Map<String, Object> linkBusinessMap = fieldAttr.getLinkBusinessMap();
        if (Objects.isNull(cellValue) || Objects.equals(cellValue,"")) {
            if (Objects.equals(fieldAttr.getRequired(), 1)) {
                throw new XbbException(InvoiceErrorCodeEnum.API_ERROR_217004.getCode(), InvoiceErrorCodeEnum.API_ERROR_217004.getMsg(), fieldAttr.getAttrName());
            }
            return 0L;
        }
        if (linkBusinessMap.containsKey(cellValue)) {
            JSONArray linkBusinessArr = new JSONArray();
            JSONObject linkSupplierObj = new JSONObject();
            linkSupplierId = Long.valueOf(linkBusinessMap.get(cellValue).toString());
            linkSupplierObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, linkBusinessMap.get(cellValue));
            linkSupplierObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, cellValue);
            linkBusinessArr.add(linkSupplierObj);
            dataJson.put(fieldAttr.getAttr(), linkBusinessArr);
        } else {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_EXISTS_IN_SYSTEM, fieldAttr.getAttrName());
        }
        return linkSupplierId;
    }

    public JSONArray getFieldAttrList(String corpid) throws XbbException {
        List<FieldAttrEntity> subItems = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        ProductFieldPojo priceFieldPojo = saasFormHelp.getProductFieldPojo(RedisPrefixConstant.PRODUCT_PRICE, ProductEnum.PRICE.getAttr(), corpid);
        for (PriceProductEnum priceProductEnum : PriceProductEnum.values()) {
            if (Objects.equals(priceProductEnum.getAttr(), PriceProductEnum.PARENT_ID.getAttr())) {
                continue;
            }
            FieldAttrEntity fieldAttrEntity = new FieldAttrEntity();
            fieldAttrEntity.setAttr(priceProductEnum.getAttr());
            fieldAttrEntity.setAttrName(priceProductEnum.getAttrName());
            fieldAttrEntity.setSaasAttr(priceProductEnum.getSaasAttr());
            fieldAttrEntity.setFieldType(priceProductEnum.getFieldType());
            fieldAttrEntity.setSort(priceProductEnum.getSort());
            fieldAttrEntity.setVisible(priceProductEnum.getVisible());
            fieldAttrEntity.setRequired(priceProductEnum.getRequired());
            fieldAttrEntity.setEditable(priceProductEnum.getEditable());
            fieldAttrEntity.setSaasMark(SaasMarkEnum.SAAS.getCode());
            fieldAttrEntity.setParentAttr(PriceSetEnum.PRODUCT.getAttr());
            if (Objects.equals(priceProductEnum.getAttr(), PriceProductEnum.NAME.getAttr())) {
                fieldAttrEntity.setFieldType(FieldTypeEnum.TEXT.getType());
            } else if (Objects.equals(priceProductEnum.getFieldType(), FieldTypeEnum.NUM.getType())){
                fieldAttrEntity.setAccuracy(priceFieldPojo.getAccuracy());
            }

            subItems.add(fieldAttrEntity);
        }
        List<FieldAttrEntity> fieldAttrList = new ArrayList<>();
        for (PriceSetEnum value : PriceSetEnum.values()) {
            FieldAttrEntity fieldAttrEntity = new FieldAttrEntity();
            fieldAttrEntity.setAttr(value.getAttr());
            fieldAttrEntity.setAttrName(value.getAttrName());
            fieldAttrEntity.setSaasAttr(value.getSaasAttr());
            fieldAttrEntity.setFieldType(value.getFieldType());
            fieldAttrEntity.setSort(value.getSort());
            fieldAttrEntity.setVisible(value.getVisible());
            fieldAttrEntity.setRequired(value.getRequired());
            fieldAttrEntity.setEditable(value.getEditable());
            fieldAttrEntity.setSaasMark(SaasMarkEnum.SAAS.getCode());
            if (Objects.equals(PriceSetEnum.PRODUCT.getAttr(), value.getAttr())) {
                SubFormPoJo subFormPoJo = new SubFormPoJo();
                subFormPoJo.setItems(subItems);
                fieldAttrEntity.setSubForm(subFormPoJo);
            }else if (Objects.equals(value.getAttr(), PriceSetEnum.ADAPTER_TYPE.getAttr()) && Objects.equals(FieldTypeEnum.COMBO.getType(), value.getFieldType())) {
                fieldAttrEntity.setComboType(0);
                List<PaasFormEntityExt> templateList = paasFormModel.getEnableFormList(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                List<ItemPoJo> items = new ArrayList<>();
                for (PaasFormEntityExt paasFormEntityExt : templateList) {
                    ItemPoJo itemPoJo = new ItemPoJo();
                    itemPoJo.setText(paasFormEntityExt.getName());
                    itemPoJo.setValue(paasFormEntityExt.getId());
                    items.add(itemPoJo);
                }
                fieldAttrEntity.setItems(items);
            }
            fieldAttrList.add(fieldAttrEntity);
        }
        return JSON.parseArray(JSON.toJSONString(fieldAttrList));
    }

    public void formatLinkData(Object cellValue, FieldAttrEntityForImport fieldAttrEntityForImport, JSONObject dataJson) throws XbbException{
        DataPermissionParamsPojo dataPermissionParamsPojoValue = TransmittableThreadLocalUtil.getDataPermissionParamsPojoValue();
        String corpid = dataPermissionParamsPojoValue.getCorpid();
        String attr = fieldAttrEntityForImport.getAttr();
        LinkInfoPojo linkInfoPojo = fieldAttrEntityForImport.getLinkInfo();
        String keyAttr = linkInfoPojo.getLinkKey();
        Long linkFormId = linkInfoPojo.getLinkFormId();
        Integer linkSaasMark = linkInfoPojo.getLinkSaasMark();
        Integer linkBusinessType = linkInfoPojo.getLinkBusinessType();
        String keyWord = StringConstant.POINT + StringConstant.KEY_WORD;
        String formHashKey = corpid + "_" + dataPermissionParamsPojoValue.getUserId() + "_" + dataPermissionParamsPojoValue.getFormId() + "_" + Thread.currentThread().getId() ;
        //设置IndexTypeEnum
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, linkBusinessType, linkSaasMark);
        //关联数据字段个数计数
        int linkDataFieldNum = 0;
        String nowNum = paasRedisHelper.getValue(RedisPrefixConstant.LINK_DATA_NUM, formHashKey);
        if (Objects.isNull(nowNum)){
            linkDataFieldNum ++;
            paasRedisHelper.setValue(RedisPrefixConstant.LINK_DATA_NUM, formHashKey, linkDataFieldNum, RedisConstant.ONE_MIN);
        }else {
            linkDataFieldNum = Integer.valueOf(nowNum) + 1;
            paasRedisHelper.setValue(RedisPrefixConstant.LINK_DATA_NUM, formHashKey, linkDataFieldNum, RedisConstant.ONE_MIN);
            if (linkDataFieldNum > ImportConstant.MAX_LINK_DATA_NUM){
                throw  new XbbException(ImportErrorCodeEnum.API_ERROR_235060, String.format(ImportErrorCodeEnum.API_ERROR_235060.getMsg(), ImportConstant.MAX_LINK_DATA_NUM));
            }
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //获取关联表单的表单解释
        PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, linkInfoPojo.getLinkFormId(), linkBusinessType);
        if ( Objects.isNull(paasFormExplainEntity) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
        FieldAttrEntity keyFieldAttrEntity = explainMap.get(keyAttr);
        //封装查询条件
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyWord, corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.FORMID, linkInfoPojo.getLinkFormId()));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        //封装主键字段查询条件
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(linkInfoPojo.getLinkKeyAttr().getFieldType());
        switch (fieldTypeEnum) {
            case NUM:
                if (StringUtil.isDouble(cellValue.toString())) {
                    boolQueryBuilder.filter(termQuery("data." + keyAttr, Double.valueOf(cellValue.toString())));
                } else if (StringUtil.isNumeric(cellValue.toString())) {
                    boolQueryBuilder.filter(termQuery("data." + keyAttr, Long.valueOf(cellValue.toString())));
                }
                break;
            case SERIALNO:
                boolQueryBuilder.filter(termQuery(keyAttr + keyWord, cellValue));
                break;
            case COMBO:
            case RADIO_GROUP:
                Object customItemValue = ItemUtil.getCustomItemValue(keyFieldAttrEntity, String.valueOf(cellValue));
                if (Objects.nonNull(customItemValue)){
                    boolQueryBuilder.filter(termQuery("data." + keyAttr + keyWord, customItemValue));
                }
                break;
            case STAGE_THRUSTER:
                keyFieldAttrEntity.setItems(proFormHelp.getEnableStageComboItems(linkSaasMark, linkBusinessType, corpid, linkFormId));
                Object stageCode = ItemUtil.getCustomItemValue(keyFieldAttrEntity, String.valueOf(cellValue));
                if (Objects.nonNull(stageCode)){
                    boolQueryBuilder.filter(termQuery("data." + keyAttr + keyWord, stageCode));
                }
                break;
            default:
                boolQueryBuilder.filter(termQuery("data." + keyAttr + keyWord, cellValue));
                break;
        }

        // 产品有父子产品 关联数据是产品表单的时候 需要写死一个num_3 != 0 的bool条件 表示查询的是子产品 否则查询多条数据会报错
        if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), linkBusinessType)) {
            boolQueryBuilder.mustNot(termQuery("data." + ProductEnum.PARENT_ID.getAttr(), BasicConstant.ZERO));
        }

        if (commonHelp.isOpenWorkFlow(corpid)) {
            // 如果开启了工作流，审批中数据会进入主表，查重的时候可以直接从主表查到
            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType(), FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
        } else {
            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        }

        List<PaasFormDataEntity> dataList = paasEsModel.getDataList(boolQueryBuilder, indexTypeEnum, new ArrayList<>(), BasicConstant.ZERO, BasicConstant.TWO, PaasFormDataEntity.class, null, null);
        if (CollectionsUtil.isEmpty(dataList)){
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235059, String.format(ImportErrorCodeEnum.API_ERROR_235059.getMsg(), fieldAttrEntityForImport.getAttrName()));
        }
        if (dataList.size() > BasicConstant.ONE){
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235061, String.format(ImportErrorCodeEnum.API_ERROR_235061.getMsg(), fieldAttrEntityForImport.getAttrName()));
        }
        PaasFormDataEntity paasFormDataEntity = dataList.get(0);
        dataJson.put(attr, paasFormDataEntity.getDataId());

    }


    /**
     * 关联数据多选数据转换
     *
     * @param cellValue                关联数据多选值
     * @param importFormDataDTO        导入表单DTO
     * @param fieldAttrEntityForImport 导入字段属性
     * @param dataJson                 Json数据
     * @throws XbbException
     */
    public void formatLinkDataMulti(Object cellValue, ImportFormDataDTO importFormDataDTO, FieldAttrEntityForImport fieldAttrEntityForImport, JSONObject dataJson) throws XbbException {
        String[] cellArray = Arrays.stream(cellValue.toString().split(StringConstant.COMMA)).distinct().toArray(String[]::new);
        //单数据关联数据多选最大条数10
        if (cellArray.length > ImportConstant.MAX_DATA_LINK_DATA_MULTI_NUM) {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235062, ImportErrorCodeEnum.API_ERROR_235062.getMsg());
        }
        String corpid = importFormDataDTO.getCorpid();
        String attr = fieldAttrEntityForImport.getAttr();
        LinkInfoPojo linkInfoPojo = fieldAttrEntityForImport.getLinkInfo();
        String keyAttr = linkInfoPojo.getLinkKey();
        Long linkFormId = linkInfoPojo.getLinkFormId();
        Integer linkSaasMark = linkInfoPojo.getLinkSaasMark();
        Integer linkBusinessType = linkInfoPojo.getLinkBusinessType();
        String keyWord = StringConstant.POINT + StringConstant.KEY_WORD;
        String formHashKey = corpid + "_" + importFormDataDTO.getUserId() + "_" + importFormDataDTO.getFormId() + "_" + Thread.currentThread().getId();
        String attrName = fieldAttrEntityForImport.getAttrName();
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, linkBusinessType, linkSaasMark);
        //单表单关联数据多选最大数量5
        int linkDataFieldNum = 0;
        String nowNum = paasRedisHelper.getValue(RedisPrefixConstant.LINK_DATA_MULTI_NUM, formHashKey);
        if (Objects.isNull(nowNum)) {
            linkDataFieldNum++;
            paasRedisHelper.setValue(RedisPrefixConstant.LINK_DATA_MULTI_NUM, formHashKey, linkDataFieldNum, RedisConstant.ONE_MIN);
        } else {
            linkDataFieldNum = Integer.parseInt(nowNum) + 1;
            paasRedisHelper.setValue(RedisPrefixConstant.LINK_DATA_MULTI_NUM, formHashKey, linkDataFieldNum, RedisConstant.ONE_MIN);
            if (linkDataFieldNum > ImportConstant.MAX_FORM_LINK_DATA_MULTI_NUM) {
                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235063, String.format(ImportErrorCodeEnum.API_ERROR_235063.getMsg(), ImportConstant.MAX_FORM_LINK_DATA_MULTI_NUM));
            }
        }
        //获取关联表单的表单解释
        PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, linkInfoPojo.getLinkFormId(), linkBusinessType);
        if (Objects.isNull(paasFormExplainEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
        FieldAttrEntity keyFieldAttrEntity = explainMap.get(keyAttr);
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(linkInfoPojo.getLinkKeyAttr().getFieldType());
        //封装基础查询条件
        BoolQueryBuilder boolQueryBuilder = baseBoolQuery(keyWord, corpid, linkFormId, linkBusinessType);
        //封装数据查询条件
        BoolQueryBuilder subBoolQueryBuilder = boolQuery();
        //文本值和数据值的映射
        Map<Object, String> dataMap = new HashMap<>(cellArray.length);
        String esKey;
        switch (fieldTypeEnum) {
            case NUM:
                esKey = "data." + keyAttr;
                for (String cell : cellArray) {
                    Double esValue = Double.valueOf(cell);
                    subBoolQueryBuilder.should(termQuery(esKey, esValue));
                    dataMap.put(esValue, cell);
                }
                break;
            case SERIALNO:
                esKey = keyAttr + keyWord;
                for (String cell : cellArray) {
                    subBoolQueryBuilder.should(termQuery(esKey, cell));
                    dataMap.put(cell, cell);
                }
                break;
            case COMBO:
            case RADIO_GROUP:
                esKey = "data." + keyAttr + keyWord;
                for (String cell : cellArray) {
                    Object customItemValue = ItemUtil.getCustomItemValue(keyFieldAttrEntity, String.valueOf(cell));
                    if (Objects.nonNull(customItemValue)) {
                        subBoolQueryBuilder.should(termQuery(esKey, customItemValue));
                        dataMap.put(customItemValue, cell);
                    }
                }
                break;
            case STAGE_THRUSTER:
                keyFieldAttrEntity.setItems(proFormHelp.getEnableStageComboItems(linkSaasMark, linkBusinessType, corpid, linkFormId));
                esKey = "data." + keyAttr + keyWord;
                for (String cell : cellArray) {
                    Object stageCode = ItemUtil.getCustomItemValue(keyFieldAttrEntity, String.valueOf(cell));
                    if (Objects.nonNull(stageCode)) {
                        subBoolQueryBuilder.should(termQuery(esKey, stageCode));
                        dataMap.put(stageCode, cell);
                    }
                }
                break;
            default:
                esKey = "data." + keyAttr + keyWord;
                for (String cell : cellArray) {
                    subBoolQueryBuilder.should(termQuery(esKey, cell));
                    dataMap.put(cell, cell);
                }
                break;
        }
        //获取数据并校验
        dataJson.put(attr, getDataAndValidate(boolQueryBuilder.filter(subBoolQueryBuilder), indexTypeEnum, dataMap, attrName, esKey, cellArray.length));
    }

    /**
     * 封装基础查询条件
     *
     * @param keyWord
     * @param corpid
     * @param linkFormId
     * @return
     */
    private BoolQueryBuilder baseBoolQuery(String keyWord, String corpid, Long linkFormId, Integer linkBusinessType) {
        BoolQueryBuilder boolQueryBuilder = boolQuery()
                .filter(termQuery(ParameterConstant.CORPID + keyWord, corpid))
                .filter(termQuery(ParameterConstant.FORMID, linkFormId))
                .filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));

        // 产品有父子产品 关联数据是产品表单的时候 需要写死一个num_3 != 0 的bool条件 表示查询的是子产品 否则查询多条数据会报错
        if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), linkBusinessType)) {
            boolQueryBuilder.mustNot(termQuery("data." + ProductEnum.PARENT_ID.getAttr(), BasicConstant.ZERO));
        }
        return boolQueryBuilder;
    }

    /**
     * 获取数据并校验
     *
     * @param boolQueryBuilder 查询条件
     * @param indexTypeEnum 索引类型
     * @param dataMap 文本值和数据值的映射
     * @param attrName 属性名
     * @param esKey es键
     * @param dataSize 数据大小
     */
    private List<Long> getDataAndValidate(BoolQueryBuilder boolQueryBuilder, IndexTypeEnum indexTypeEnum, Map<Object, String> dataMap, String attrName, String esKey, Integer dataSize) throws XbbException {
        //添加聚合条件 类似group by
        TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms(esKey).field(esKey).size(dataSize);
        //从ES查询数据和聚合结果
        XbbAggregatedPage<PaasFormDataEntity> dataAndAggregation = paasEsModel.getDataAndAggregation(boolQueryBuilder, aggregationBuilder, indexTypeEnum,
                new ArrayList<>(), BasicConstant.ZERO, BasicConstant.TEN, PaasFormDataEntity.class, null, null);
        ParsedTerms aggregation = dataAndAggregation.getAggregations().get(esKey);
        List<? extends Terms.Bucket> buckets = aggregation.getBuckets();
        //数据存在一对多则报错
        for (Terms.Bucket bucket : buckets) {
            Object bucketKey = bucket.getKey();
            if (bucket.getDocCount() > BasicConstant.ONE) {
                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235065, String.format(ImportErrorCodeEnum.API_ERROR_235065.getMsg(), attrName, dataMap.get(bucketKey)));
            }
            dataMap.remove(bucketKey);
        }
        //数据缺失则报错
        if (!dataMap.isEmpty()){
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235064, String.format(ImportErrorCodeEnum.API_ERROR_235064.getMsg(), attrName,
                    dataMap.values().stream().reduce("", (a, b) -> a + StringConstant.COMMA + b)));
        }
        return dataAndAggregation.getContent().stream().map(PaasFormDataEntity::getId).collect(Collectors.toList());
    }
}
